Ignoring phone number if 1 is at the front - text

I am trying to send out a text message to phone numbers. It works as long as it is under 11 digits, but if the phone number has 11 digits it fails. Is there a way to be flexible for both?
$phonenum = "16783293991"; //works if 6783293991
$from_name = "Gregory Smith";
$from_email = "myemail#gmail.com";
$from = sprintf ("From: %s <%s>\nSender: %s <%s>\nContent-Type: text/plain; charset=\"UTF-8\"\nContent-Transfer-Encoding: 8bit\n", $from_name, $from_email, $from_name, $from_email);
$to = $phonenum;
$formatted_number = $to."#messaging.sprintpcs.com";
mail("$formatted_number", "", "$message", $from); //the empty field of "" is the subject line and is unnecessary

Check for 1 as the first digit, and verify length:
if ((substr($phone, 0 , 1) == '1') && (strlen($phone) <= 11)) {
sms stuff here
}

Related

How do I count number of words in a string in Typescript without counting extraneous spaces?

I have seen many cases where people sometimes rely on whitespaces which causes some miscalculations.
For Example, take 2 strings;
const str1: string = 'I love stackoverflow'
const str2: string = 'I love stackoverflow'
Using the numOfWhitespaces + 1 thing gives wrong number of words in case of str2. The reason is obvious that it counts 6 number of spaces.
So what should be an easy and better alternative?
The shortest would be using: str1.split(/\s+/).length
But just in case any beginner want to do it with basic loop, here it is:
let str1: string = 'I love stackoverflow'
let numberOfSpaces: number = 0
for (let index = 1; index <= str1.length; index++) {
let lastChar: string = ''
let currentChar: string = ''
currentChar = str1.charAt(index)
lastChar = str1.charAt(index - 1)
if (currentChar === " " && lastChar !== " ") {
numberOfSpaces = numberOfSpaces+ 1
}
else if (currentChar === " " && lastChar === " ") { // This is a test String.
numberOfSpaces = numberOfSpaces + 0
}
//I have not added an else statement for the case if both current char and last char are not whitespaces.
//because I felt there was no need for that and it works perfectly.
}
const finalNumberOfWords: number = numberOfSpaces + 1
console.log(`Number of words final are = ${finalNumberOfWords}`)
So this might look similar to the counting whitespaces method, yes it is but this one doesn't count the extraneous spaces [space followed by a space].
A for loop runs throughout the length of the string. It compares the character at current position of str1[index]and its previous index. If both are whitespaces, it won't count but if previous character was non-null and current is blank, it increments the counter by one.
And finally we add 1 to the counter to display number of words.
Here's a screenshot:
An alternative solution would be to use a regex:
const str2: string = 'I love stackoverflow'
console.log(str2.split(/\s+/).length);
This will ensure that multiple spaces will be splitted.
Test:
console.log('I love stackoverflow'.split(/\s+/).length);
console.log('Ilovestackoverflow'.split(/\s+/).length);

How to convert string to binary representation in game maker?

I found a script that converts binary to string but how can I input a string and get the binary representation? so say I put in "P" I want it to output 01010000 as a string.
I have this but it is not what I am trying to do - it converts a string containing a binary number into a real value of that number:
///string_to_binary(string)
var str = argument0;
var output = "";
for(var i = 0; i < string_length(str); i++){
if(string_char_at(str, i + 1) == "0"){
output += "0";
}
else{
output += "1";
}
}
return real(output);
Tip: search for GML or other language term, these questions answered many times. Also please check your tag as it is the IDE tag, not language tag.
Im not familiar with GML myself, but a quick search showed this:
At least semi-official method for exactly this: http://www.gmlscripts.com/script/bytes_to_bin
/// bytes_to_bin(str)
//
// Returns a string of binary digits, 1 bit each.
//
// str raw bytes, 8 bits each, string
//
/// GMLscripts.com/license
{
var str, bin, p, byte;
str = argument0;
bin = "";
p = string_length(str);
repeat (p) {
byte = ord(string_char_at(str,p));
repeat (8) {
if (byte & 1) bin = "1" + bin else bin = "0" + bin;
byte = byte >> 1;
}
p -= 1;
}
return bin;
}
GML forum (has several examples) https://www.reddit.com/r/gamemaker/comments/4opzhu/how_could_i_convert_a_string_to_binary/
///string_to_binary(string)
var str = argument0;
var output = "";
for(var i = 0; i < string_length(str); i++){
if(string_char_at(str, i + 1) == "0"){
output += "0";
}
else{
output += "1";
}
}
return real(output);
And other language examples:
C++ Fastest way to Convert String to Binary?
#include <string>
#include <bitset>
#include <iostream>
using namespace std;
int main(){
string myString = "Hello World";
for (std::size_t i = 0; i < myString.size(); ++i)
{
cout << bitset<8>(myString.c_str()[i]) << endl;
}
}
Java: Convert A String (like testing123) To Binary In Java
String s = "foo";
byte[] bytes = s.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes)
{
int val = b;
for (int i = 0; i < 8; i++)
{
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
binary.append(' ');
}
System.out.println("'" + s + "' to binary: " + binary);
JS: How to convert text to binary code in JavaScript?
function convert() {
var output = document.getElementById("ti2");
var input = document.getElementById("ti1").value;
output.value = "";
for (var i = 0; i < input.length; i++) {
output.value += input[i].charCodeAt(0).toString(2) + " ";
}
}
I was looking around for a simple GML script to convert a decimal to binary and return the bits in an array. I didn't find anything for my need and to my liking so I rolled my own. Short and sweet.
The first param is the decimal number (string or decimal) and the second param is the bit length.
// dec_to_bin(num, len);
// argument0, decimal string
// argument1, integer
var num = real(argument0);
var len = argument1;
var bin = array_create(len, 0);
for (var i = len - 1; i >= 0; --i) {
bin[i] = floor(num % 2);
num -= num / 2;
}
return bin;
Usage:
dec_to_bin("48", 10);
Output:
{ { 0,0,0,0,1,1,0,0,0,0 }, }
i think the binary you mean is the one that computers use, if thats the case, just use the common binary and add a kind of identification.
binary is actually simple, instead of what most people think.
every digit represents the previous number *2 (2¹, 2², 2³...) so we get:
1, 2, 4, 8, 16, 32, 64, 128, 256, 512...
flip it and get:
...512, 256, 128, 64, 32, 16, 8, 4, 2, 1
every digit is "activated" with 1's, plus all the activated number ant thats the value.
ok, so binary is basically another number system, its not like codes or something. Then how are letters and other characters calculated?
they arent ;-;
we just represent then as their order on their alphabets, so:
a=1
b=2
c=3
...
this means that "b" in binary would be "10", but "2" is also "10". So thats where computer's binary enter.
they just add a identification before the actual number, so:
letter_10 = b
number_10 = 2
signal_10 = "
wait, but if thats binary there cant be letter on it, instead another 0's and 1's are used, so:
011_10 = b
0011_10 = 2
001_10 = "
computers also cant know where the number starts and ends, so you have to always use the same amount of numbers, which is 8. now we get:
011_00010 = b
0011_0010 = 2
001_00010 = "
then remove the "_" cuz again, computers will only use 0's and 1's. and done!
so what i mean is, just use the code you had and add 00110000 to the value, or if you want to translate these numbers to letters as i wanted just add 01100000
in that case where you have the letter and wants the binary, first convert the letter to its number, for it just knows that the letters dont start at 1, capitalized letters starts at 64 and the the non-capitalized at 96.
ord("p")=112
112-96=16
16 in binary is 10000
10000 + 01100000 = 01110000
"p" in binary is 01110000
ord("P")=80
80-64=16
16 in binary is 10000
10000 + 01000000 = 01010000
"P" in binary is 01010000
thats just a explanation of what the code should do, actually im looking for a simple way to turn binary cuz i cant understand much of the code you showed.
(011)
1000 1111 10000 101 1001 1000 101 1100 10000 101 100

Swift - Search in string and sum the numbers

Hey guys I have string "69 - 13" How to detect "-" in the string and how to sum the numbers in the string 69+13=82 ?
There are various method to do that (componentsSeparatedByString, NSScanner, ...).
Here is one using only Swift library functions:
let str = "69 - 13"
// split string into components:
let comps = split(str, { $0 == "-" || $0 == " " }, maxSplit: Int.max, allowEmptySlices: false)
// convert strings to numbers (use zero if the conversion fails):
let nums = map(comps) { $0.toInt() ?? 0 }
// compute the sum:
let sum = reduce(nums, 0) { $0 + $1 }
println(sum)
Here is an updated implementation in Swift 4 that relies on higher order functions to perform the operation:
let string = "69+13"
let number = string.components(separatedBy: CharacterSet.decimalDigits.inverted)
.compactMap({ Int($0) })
.reduce(0, +)
print(number) // 82
The components(separatedBy: CharacterSet.decimalDigits.inverted) removes all non-digit values and creates an array for each group of values (in this case 69 and 13)
Int($0) converts your string value into an Int
compactMap gets rid of any nil values, ensuring that only valid values are left
reduce then sums up the values that remain in your array

Transpose column to row into Formatted Output:

Would like to transpose below Non formatted Input into Formatted Output, since it is having multiple de-limited,
got struck to proceed further and looking for your suggestions.
Sample_Input.txt
UMTSGSMPLMNCallDataRecord
callForwarding
chargeableDuration 0 4 44'BCD
dateForStartOfCharge 09011B'H
recordSequenceNumber 57526'D
UMTSGSMPLMNCallDataRecord
mSTerminating
chargeableDuration 0 4 44'BCD
dateForStartOfCharge 09011B'H
recordSequenceNumber 57573'D
originalCalledNumber 149212345678'TBCD
redirectingNumber 149387654321'TBCD
!!!!!!!!!!!!!!!!!!!!!!!!1164!!!!!!!!!!!!!!!!!!!!!!
UMTSGSMPLMNCallDataRecord
mSTerminating
chargeableDuration 0 0 52'BCD
dateForStartOfCharge 09011B'H
recordSequenceNumber 45761'D
tariffClass 2'D
timeForStartOfCharge 9 46 58'BCD
calledSubscriberIMSI 21329701412F'TBCD
Searched in previous questions and got some relavent inputs from Mr.Porges Answer:
#!/bin/sh
# split lines on " " and use "," for output field separator
awk 'BEGIN { FS = " "; i = 0; h = 0; ofs = "," }
# empty line - increment item count and skip it
/^\s*$/ { i++ ; next }
# normal line - add the item to the object and the header to the header list
# and keep track of first seen order of headers
{
current[i, $1] = $2
if (!($1 in headers)) {headers_ordered[h++] = $1}
headers[$1]
}
END {
h--
# print headers
for (k = 0; k <= h; k++)
{
printf "%s", headers_ordered[k]
if (k != h) {printf "%s", ofs}
}
print ""
# print the items for each object
for (j = 0; j <= i; j++)
{
for (k = 0; k <= h; k++)
{
printf "%s", current[j, headers_ordered[k]]
if (k != h) {printf "%s", ofs}
}
print ""
}
}' Sample_Input.txt
Am getting below output:
UMTSGSMPLMNCallDataRecord,callForwarding,chargeableDuration,dateForStartOfCharge,recordSequenceNumber,mSTerminating,originalCalledNumber,redirectingNumber,!!!!!!!!!!!!!!!!!!!!!!!!1164!!!!!!!!!!!!!!!!!!!!!!,tariffClass,timeForStartOfCharge,calledSubscriberIMSI
,,,,,,,,,,,
,,0,09011B'H,57526'D,,,,,,,
,,,,,,,,,,,
,,,,,,,,,,,
,,,,,,,,,,,
,,0,09011B'H,57573'D,,149212345678'TBCD,149387654321'TBCD,,,,
,,,,,,,,,,,
,,,,,,,,,,,
,,,,,,,,,,,
,,,,,,,,,,,
,,,,,,,,,,,
,,0,09011B'H,45761'D,,,,,2'D,9,21329701412F'TBCD
,,,,,,,,,,,
where it stucks,
(a). Need to tackle when the block starts like "UMTSGSMPLMNCallDataRecord" and Empty Field , then the next line words like callForwarding/mSTerminating etc and Empty Field,
First word need to be considered as Row ("UMTSGSMPLMNCallDataRecord" ) and next line word need to be considered as Column (callForwarding/mSTerminating)
(b). Need to avoid the ALPHAPET into column fields i.e 09011B'H into 09011 , 149212345678'TBCD into 149212345678
Expected Output:
UMTSGSMPLMNCallDataRecord,chargeableDuration,dateForStartOfCharge,recordSequenceNumber,originalCalledNumber,redirectingNumber,tariffClass,timeForStartOfCharge,calledSubscriberIMSI
callForwarding,0 4 44,09011,57526,,,,,
mSTerminating,0 4 44,09011,57573,149212345678,149387654321,,,
mSTerminating,0 0 52, 09011,45761,,,2,9 46 58,21329701412
Edit:I have tried on the below Input:
UMTSGSMPLMNCallDataRecord
callForwarding
chargeableDuration 0 4 44'BCD
dateForStartOfCharge 09011B'H
recordSequenceNumber 57526'D
UMTSGSMPLMNCallDataRecord
mSTerminating
chargeableDuration 0 4 44'BCD
dateForStartOfCharge 09011B'H
recordSequenceNumber 57573'D
originalCalledNumber 149212345678'TBCD
redirectingNumber 149387654321'TBCD
!!!!!!!!!!!!!!!!!!!!!!!!1164!!!!!!!!!!!!!!!!!!!!!!
UMTSGSMPLMNCallDataRecord
mSTerminating
chargeableDuration 0 0 52'BCD
dateForStartOfCharge 09011B'H
recordSequenceNumber 45761'D
tariffClass 2'D
timeForStartOfCharge 9 46 58'BCD
calledSubscriberIMSI 21329701412F'TBCD
Discussion
This is a complex problem since the records are non-uniform: some with missing fields. Since each record occupies several lines, we can deal with it using AWK's multi-records feature: by setting the RS (record separator) and FS (field separator) variables.
Next, we need to deal with collecting the header fields. I don't have a good way to do this, so I hard-code the header line.
Once we establish the order in the header, we need a way to extract a specific field from the record and we accomplish that via the function get_column(). This function also strip off non-numeric data at the end per your requirement.
One last thing, we need to trim the white spaces off the first column ($2) using the homemade trim() function.
Command Line
I placed my code in make_csv.awk. To run it:
awk -f make_csv.awk Sample_Input.txt
File make_csv.awk
BEGIN {
# Next two lines: each record is of multiple lines, each line is a
# separate field
RS = ""
FS = "\n"
print "UMTSGSMPLMNCallDataRecord,chargeableDuration,dateForStartOfCharge,recordSequenceNumber,originalCalledNumber,redirectingNumber,tariffClass,timeForStartOfCharge,calledSubscriberIMSI"
}
function get_column(name, i, f, len) {
# i, f and len are "local" variables
for (i = 1; i <= NF; i++) {
len = split($i, f, " ")
if (f[1] == name) {
result = f[2]
for (i = 3; i <= len; i++) {
result = result " " f[i]
}
# Remove the trailing non numeric data
sub(/[a-zA-Z']+/, "", result)
return result
}
}
return "" # get_column not found, return empty string
}
# Remove leading and trailing spaces
function trim(s) {
sub(/[ \t]+$/, "", s)
sub(/^[ \t]+/, "", s)
return s
}
/UMTSGSMPLMNCallDataRecord/ {
print trim($2) \
"," get_column("chargeableDuration") \
"," get_column("dateForStartOfCharge") \
"," get_column("recordSequenceNumber") \
"," get_column("originalCalledNumber") \
"," get_column("redirectingNumber") \
"," get_column("tariffClass") \
"," get_column("timeForStartOfCharge") \
"," get_column("calledSubscriberIMSI") \
""
}
Update
I tried out my AWK script against AVN's latest input and got the following output:
UMTSGSMPLMNCallDataRecord,chargeableDuration,dateForStartOfCharge,recordSequenceNumber,originalCalledNumber,redirectingNumber,tariffClass,timeForStartOfCharge,calledSubscriberIMSI
callForwarding,0 4 44,09011,57526,,,,,
mSTerminating,0 4 44,09011,57573,149212345678,149387654321,,,
mSTerminating,0 0 52,09011,45761,,,2,9 46 58,21329701412

Two digit numbers [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I need a program that takes a two digit number such as "22" and returns "Twenty Two". I have the following started for the main method but have nothing for the string method
static string TwoDigit(int n)
{
}
static void Main(string[] args)
{
for (int i = 0; i <= 19; i++)
Console.WriteLine("{0}: {1}", i, TwoDigit(i));
for (int i = 20; i <= 110; i += 7)
Console.WriteLine("{0}: {1}", i, TwoDigit(i));
}
I don't know of an existing program but it would be easy to write the function.
I would convert the int to a string then do a switch statement on each character.
The first switch would handle the "Twenty", "Thirty", etc.
The second switch would handle one, two, three, etc.
You will need to have a special case for the teens that just spits out the word for each.
Just take time in your reseach. If you don't know how to do it, I would advise to parse the int number by one number and then format the text via case.
switch (int)
case 1:
cout << "one";
switch (int)
case 2:
cout << "two";
It would be easiest to just evaluate both digits separately and match them up to string values stored in two arrays.
So for example, you might have these two arrays...
tens[0] = ""
tens[1] = ""
tens[2] = "Twenty"
tens[3] = "Thirty"
tens[4] = "Forty"
tens[5] = "Fifty"
tens[6] = "Sixty"
etc...
ones[0] = ""
ones[1] = "One"
ones[2] = "Two"
ones[3] = "Three"
etc...
And then if the number is >= 20, you can simply take the first digit and use it as your index for the tens array, and your second digit and use it as your index for your ones array. If the number is between 10 and 19, you'll need some special logic to handle it.
Initialize this function
function Ones_String(number1) {
if (number1 == 1) {
string1 = "One";
} elseif (number2 == 9) {
string1 = "Nine";
} elseif (number2 == 10) {
string1 = "Ten";
} elseif (number2 == 0) {
string1 = "Zero";
} else {
string1 = ""; // empty value
}
return string1;
}
function Tens_String(number2) {
if (number2 == 2) {
string2 = "Twenty";
} elseif (number2 == 3) {
string2 = "Thirty";
} elseif (number2 == 9) {
string2 = "Ninety";
} else {
string2 = ""; // emtpy value
}
return string2;
}
function teens_string(number3) {
if (number3 == 11) {
string3 = "Eleven";
} elseif (number3 == 12) {
string3 = "Tweleve";
} else {
string3 = "Nineteen";
}
return string3;
}
If given number < 11 then call Ones_string()
If it is number >= 11 then do below logic
First : get the seconds digit value and call Tens_String();
Second : get the first digit vallue and call Ones_string();
And this algorithm applies till 99 .. Last used in 2006 at College on C++..
Whatever i mentioned is an algorithm / logic to detect.. not the perfect code

Resources