I am making a calculator and unable to seperate the input string in corrosponding to operands.
For example : 2*5 - 6 +8/2. I want an array with components 2, 5, 6, 8, 2 so that I can store the oprators also and then sort accordingly. Please help
NSString *str=#"2*5 - 6 +8/2"; // assume that this is your str
// here remove the white space
str =[str stringByReplacingOccurrencesOfString:#" " withString:#""];
// here remove the all special characters in NSString
NSCharacterSet *noneedstr = [NSCharacterSet characterSetWithCharactersInString:#"*/-+."];
str = [[str componentsSeparatedByCharactersInSet: noneedstr] componentsJoinedByString:#","];
NSLog(#"the str=-=%#",str);
the out put is
the str=-=2,5,6,8,2
You can use the method, componentsSeparatedByCharactersInSet:.
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:#"*-+/"];
NSArray *numbers = [text componentsSeparatedByCharactersInSet:set];
You can get arrays of the operands and operators like so. This assumes the expression is valid, base 10, begins and ends with operands, etc. The expression would then be operands[0], operators[0], operands[1], operators[1], and so on.
NSString *expression = #"2*5 - 6 +8/2";
// Could use a custom character set as well, or -whitespaceAndNewlineCharacterSet
NSCharacterSet *whitespaceCharacterSet = [NSCharacterSet whitespaceCharacterSet];
NSArray *nonWhitespaceComponents = [expression componentsSeparatedByCharactersInSet:whitespaceCharacterSet];
NSString *trimmedExpression = [nonWhitespaceComponents componentsJoinedByString:#""];
// To get an array of the operands:
NSCharacterSet *operatorCharacterSet = [NSCharacterSet characterSetWithCharactersInString:#"+-/*"];
NSArray *operands = [trimmedExpression componentsSeparatedByCharactersInSet:operatorCharacterSet];
// To get the array of operators:
NSCharacterSet *baseTenCharacterSet = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
NSArray *operators = [trimmedExpression componentsSeparatedByCharactersInSet:baseTenCharacterSet];
// Since expression should begin and end with operands, first and last strings will be empty
NSMutableArray *mutableOperators = [operators mutableCopy];
[mutableOperators removeObject:#""];
operators = [NSArray arrayWithArray:mutableOperators];
NSLog(#"%#", operands);
NSLog(#"%#", operators);
Related
This question already has answers here:
How to remove non numeric characters from phone number in objective-c?
(5 answers)
Closed 6 years ago.
I can't remove white space from Phone Number in iOS app.
Here is my codes.
ABMultiValueRef multiPhones = ABRecordCopyValue(person, kABPersonPhoneProperty);
for (CFIndex iPhone = 0; iPhone < ABMultiValueGetCount(multiPhones); iPhone++)
{
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(multiPhones, iPhone);
NSString *phoneNumber = (__bridge NSString *) phoneNumberRef;
if (phoneNumber == nil) {
phoneNumber = #"";
}
if (phoneNumber.length == 0) continue;
// phone number = (217) 934-3234
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#"(" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#")" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#"-" withString:#""];
phoneNumber = [phoneNumber stringByReplacingOccurrencesOfString:#" " withString:#""];
// phone number = 217 9343234
[phoneNumbers addObject:phoneNumber];
}
I expect to get without white space. But it is not removed from the phone number.
How can I fix? Please help me. Thanks
You can do something a lot simpler than what you're currently doing with NSCharacterSet. Here's how:
NSCharacterSet defines a collection of characters. There are a few standard ones, such as decimalDigitsCharacterSet and alphaNumericCharacterSet.
There's also a neat method called invertedSet which returns a character set with all of the characters not included in the current one. Now, we need just one more bit of information.
NSString has a method called componentsSeparatedByCharactersInSet:, which gives you back an NSArray of the parts of the string, broken up around the characters in the characterSet you supply.
NSArray has a complementary function, componentsJoinedWithString: which you can use to turn the elements of an array (back) into a string. See where this is going?
First, define a character set that we want to include in our final output:
NSCharacterSet *digits = [NSCharacterSet decimalDigitCharacterSet];
Now, get everything else.
NSCharacterSet *illegalCharacters = [digits invertedSet]
Once we have the character set that we want, we can break out the string and reconstruct it:
NSArray *components = [phoneNumber componentsSeperatedByCharactersInSet:illegalCharacters];
NSString *output = [components componentsJoinedByString:#""];
That should give you the correct output. Four lines, and you're done:
NSCharacterSet *digits = [NSCharacterSet decimalDigitCharacterSet];
NSCharacterSet *illegalCharacters = [digits invertedSet];
NSArray *components = [phoneNumber componentsSeparatedByCharactersInSet:illegalCharacters];
NSString *output = [components componentsJoinedByString:#""];
You can use the whitespaceCharacterSet do do something similar to trim whitespace off of strings.
NSHipster has a great article about this, too.
EDIT:
If you want to include other symbols, such as the + prefix or parenthesis, you can create custom character sets with characterSetWithCharactersInString:. If you have two character sets, such as the decimal digits and the custom one you created, you could use NSMutableCharacterSet to modify the character set you have to include other characters.
My app uses addresses. I am not sure how to create a regex that strips away an address that reads like these.
" , Paxton, TX"
" , Dallas TX"
Need the above to be stripped so they read like this.
"Paxton, TX"
"Dallas TX"
Use the NSString API stringByTrimmingCharactersInSet:
NSString *test = #" , Paxton, TX";
NSMutableCharacterSet *charset = [[NSCharacterSet whitespaceCharacterSet] mutableCopy];
[charset addCharactersInString:#","];
NSString *final = [test stringByTrimmingCharactersInSet:charset];
NSLog(#"final = [%#]",final);
You can also do this without using regular expressions
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:#" ,"];
NSString *trimmed = [#" , Payton, TX" stringByTrimmingCharactersInSet:charSet];
NSLog(#"%#", trimmed); //prints "Payton, TX"
I have a UILabel with the following text:
Medium, Black
What I intended to do was grab the words in the string and insert each into a mutable array so I could use each title later on to identify something.
Here's how I done this:
NSMutableArray *chosenOptions = [[[[cell tapToEditLabel] text] componentsSeparatedByString: #" "] mutableCopy];
NSString *size = [chosenOptions objectAtIndex:0];
NSString *colour = [chosenOptions objectAtIndex:1];
I've logged these two NSString and size is returning "Medium," and colour is correctly returning "Black".
My comparison result is always false because of the comma:
itemExists = [[item colour] isEqualToString:colour] && [[item size] isEqualToString:size] ? YES : NO;
That comma causes itemExists to always equal NO.
Would appreciate a simple solution in code please.
The solution needs to only strip commas and not other characters. When dealing with clothing sizes for females I use sizes in a string like this: "[8 UK]" so remove non-alphanumeric characters would remove these. So I really need a solution to deal with just the commas.
Thanks for your time.
Rather than splitting on spaces, you could split on spaces or commas, like this:
NSMutableArray *chosenOptions = [[[[cell tapToEditLabel] text] componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#" ,"]] mutableCopy];
[chosenOptions removeObject:#""];
This would eliminate commas from the size and colour strings.
[yourString stringByReplacingOccurrencesOfString:#"," withString:#""];
easy squeezy lemon peesey
Try this:
NSString * myString = #"Medium, Black";
NSString * newString = [myString stringByReplacingOccurrencesOfString:#", " withString:#""];
NSLog(#"%#xx",newString);
How to remove character '\' in NSString IOS
For example,
NSString *abc = #"bmcvn\nmsf;
I have tried:
NSString *stri = #"\rdffsdf";
NSString *str = [stri stringByReplacingOccurrencesOfString:#"\\" withString:#"123"];
NSLog(str);
but it didn't replace
Note the difference between replacing the backslash char
NSString *original = #"foo\\bar";
NSLog(#"%#", original); // Prints: foo\bar
NSString *replaced = [original stringByReplacingOccurrencesOfString:#"\\" withString:#""];
NSLog(#"%#", replaced); // Prints: foobar
And replacing a char that is represented using a backslash (\r, \n, \t, ...):
NSString *original = #"thisIsCarriageReturn\rRightThere";
NSLog(#"%#", original); // Prints: thisIsCarriageReturn
// RightThere
NSString *replaced = [original stringByReplacingOccurrencesOfString:#"\r" withString:#""];
NSLog(#"%#", replaced); // Prints: thisIsCarriageReturnRightThere
You can't replace "\" in the string "\rdffsdf" because it is part the two character representation "\r" of the single character with the hex value 0x0d (13 decimal). It is the "carriage return" character.
When a carriage return character (0x0d) is needed in a string it is entered as "\r". Also common are the two character sequences line feed "\n" (0X0a), horizontal tab "\t" (0X09) and finally backslash "\" (0x5c).
The backslash case:
NSString *stri = #"\\rdffsdf";
NSString *str = [stri stringByReplacingOccurrencesOfString:#"\\" withString:#"123"];
NSLog(#"str: %#", str);
NSLog output:
str: 123rdffsdf
NSString *s = #"foo/bar:baz.foo";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:#"/:."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: #""];
NSLog(#"%#", s); // => foobarbazfoo
Replace multiple characters in a string in Objective-C?
Since the back slash character is an escape character you have to write two of them.
- (NSString *)sanitizeString:(NSString *)string {
NSCharacterSet* illegalCharacters = [NSCharacterSet characterSetWithCharactersInString:#"\n"];
return [[string componentsSeparatedByCharactersInSet: illegalCharacters] componentsJoinedByString:#"n"];
}
I am an iOS newbie, so please pardon me if this is a beginner level question.
I have a string "hu_HU Hungary:Hungarian" and I want to put it into an array like {"hu", "HU", "Hungary:Hungarian"}. How would I parse it to remove the whitespace and then the underscore?
Use componentsSeparatedByCharactersInSet: method of NSString
To get the desired effect you must change the '_' to a ' ' or vice versa. Then you can use componentsSeparatedByString, like so:
NSString *source = #"hu_HU Hungary:Hungarian";
source = [source stringByReplacingOccurrencesOfString:#"_" withString:#" "];
NSArray *components = [source componentsSeparatedByString:#" "];
NSLog(#"%#",components);
NSString *theStr = #"hu_HU Hungary:Hungarian";
NSArray *pieces = [theStr componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString: #"_ "]];
//pieces = {"hu", "HU", "Hungary:Hungarian"}
pieces = [theStr componentsSeparatedByCharactersInSet: [[NSCharacterSet alphanumericCharacterSet] invertedSet]];
//pieces = {"hu", "HU", "Hungary", "Hungarian"}
//the motivation for this is a better defined set of non-alphanumeric characters
Here you are:
NSString *myString = #"hu_HU Hungary:Hungarian";
myString = [myString stringByReplacingOccurrencesOfString:#"_" withString:#" "];
NSArray *myArray = [myString componentsSeparatedByString:#" "];
All of these answers share an annoying problem. They assume that the items are separated by one and only one space.
NSString *theStr = #"hu_HU Hungary:Hungarian";
NSArray *pieces = [theStr componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString: #"_ "]];
//pieces = {"hu", "HU", "Hungary:Hungarian"}
NSString *theStr = #"hu_HU Hungary:Hungarian"; // note extra space
NSArray *pieces = [theStr componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString: #"_ "]];
//pieces = {"hu", "HU", " ", "Hungary:Hungarian"}