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.
Related
For example if i had a string like
NSString *myString = #"A B C D E F G";
and I want to remove the spaces, and get a string out like "ABCDEFG".
I could use
NSString *stringWithoutSpaces = [myString stringByReplacingOccurrencesOfString:#" " withString:#""];
However, for my application I am loading in phone numbers from the address book
and the numbers often have a different formatting layout.
I'm wondering if I have a phone number stored in a string like
+1-(937)673-3451 how would I go about removing only the first "1" the "+" the "-" and the "(" ")".
Overall, I would like to know if it is possible to remove the first "1" without removing the last one in the string?
There are a lot of ways to do this. Here's one:
NSString *phoneNumber = #"+1-(937)673-3451";
NSCharacterSet *removalCharacterSet = [NSCharacterSet characterSetWithCharactersInString:#"+()-"];
NSArray *components = [phoneNumber componentsSeparatedByCharactersInSet:removalCharacterSet];
NSString *simplifiedPhoneNumber = [components componentsJoinedByString:#""];
NSRange firstCharacterRange = NSMakeRange(0, 1);
if ([[simplifiedPhoneNumber substringWithRange:firstCharacterRange] isEqualToString:#"1"]) {
simplifiedPhoneNumber = [simplifiedPhoneNumber stringByReplacingCharactersInRange:firstCharacterRange withString:#""];
}
NSLog(#"Full phone number: %#", phoneNumber);
NSLog(#"Simplified phone number: %#", simplifiedPhoneNumber);
But really you want to use a library that knows what a phone number is supposed to look like, like libPhoneNumber.
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);
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);
I have an NSString *fileName
This will contain a variable number from 1 to 3 digits. I want to extract all of the digits
I can get the first digit using
//create text for appliance identifier
char obsNumber = [fileName characterAtIndex:3];//get 4 character
NSLog(#"Obs number %c",obsNumber);
//Text label
[cell.titleLabel setText:[NSString stringWithFormat:#"Item No: %c",obsNumber]];
NSLog(#"Label for observation = %#",cell.titleLabel.text);
However if the string contains the number for example 78, or 204 I want to catch all two or three digits.
I tried this
//create text for appliance identifier
char obsNumber1 = [fileName characterAtIndex:3];//get 4 character
char obsNumber2 = [fileName characterAtIndex:4];//get 5 character
char obsNumber3 = [fileName characterAtIndex:5];//get 6 character
NSLog(#"Obs number %c,%c,%c",obsNumber1,obsNumber2,obsNumber3);
//Text label
[cell.titleLabel setText:[NSString stringWithFormat:#"Item No: %c,%c,%c",obsNumber1,obsNumber2,obsNumber3]];
NSLog(#"Label for observation = %#",cell.titleLabel.text);
This gave me 18c 1ce etc
Would this work for you?
NSString *filename = #"obs127observation"; //An example variable with your format
This code could be tidier but you should get the idea:
NSString *filenameNumber = [[filename
stringByReplacingOccurrencesOfString:#"observation"
withString:#""]
stringByReplacingOccurrencesOfString:#"obs"
withString:#""];
you can trim other letters except the decimals.
NSString *onlyNumbers=[yourstring stringByTrimmingCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
As your comment says , It has predefined set of values, right. Then try like this
NSstring *str = [filename substringFromIndex:11];
// Convert the str to char[]
Then you should try with the NSScanner :
NSString *numberString;
NSScanner *scanner = [NSScanner scannerWithString:filename];
NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
// Throw away characters before the first number.
[scanner scanUpToCharactersFromSet:numbers intoString:NULL];
// Collect numbers.
[scanner scanCharactersFromSet:numbers intoString:&numberString];
// Result.
int number = [numberString integerValue];
// you can play around with the set of number
Your approach of separating one character at a time and then combining them back into a string is an awkward, overly complex way of going about this. Kumar's suggestion of using NSScanner is a good option if you have a number in the middle of a string.
However, you make it sound like your string will always contain a number and only a number. Is that true? Or will there be characters you need to ignore?
You need to define the problem clearly and completely before you can select the best solution.
It might be as simple as using the NSString method substringWithRange.
How can I get the unique characters in an NSString?
What I'm trying to do is get all the illegal characters in an NSString so that I can prompt the user which ones were inputted and therefore need to be removed. I start off by defining an NSCharacterSet of legal characters, separate them with every occurrence of a legal character, and join what's left (only illegal ones) into a new NSString. I'm now planning to get the unique characters of the new NSString (as an array, hopefully), but I couldn't find a reference anywhere.
NSCharacterSet *legalCharacterSet = [NSCharacterSet
characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789-()&+:;,'.# "];
NSString *illegalCharactersInTitle = [[self.titleTextField.text.noWhitespace
componentsSeparatedByCharactersInSet:legalCharacterSet]
componentsJoinedByString:#""];
That should help you. I couldn't find any ready to use function for that.
NSMutableSet *uniqueCharacters = [NSMutableSet set];
NSMutableString *uniqueString = [NSMutableString string];
[illegalCharactersInTitle enumerateSubstringsInRange:NSMakeRange(0, illegalCharactersInTitle.length) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
if (![uniqueCharacters containsObject:substring]) {
[uniqueCharacters addObject:substring];
[uniqueString appendString:substring];
}
}];
Try with the following adaptation of your code:
// legal set
NSCharacterSet *legalCharacterSet = [NSCharacterSet
characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789-()&+:;,'.# "];
// test strings
NSString *myString = #"LegalStrin()";
//NSString *myString = #"francesco#gmail.com"; illegal string
NSMutableCharacterSet *stringSet = [NSCharacterSet characterSetWithCharactersInString:myString];
// inverts the set
NSCharacterSet *illegalCharacterSet = [legalCharacterSet invertedSet];
// intersection of the string set and the illegal set that modifies the mutable stringset itself
[stringSet formIntersectionWithCharacterSet:illegalCharacterSet];
// prints out the illegal characters with the convenience method
NSLog(#"IllegalStringSet: %#", [self stringForCharacterSet:stringSet]);
I adapted the method to print from another stackoverflow question:
- (NSString*)stringForCharacterSet:(NSCharacterSet*)characterSet
{
NSMutableString *toReturn = [#"" mutableCopy];
unichar unicharBuffer[20];
int index = 0;
for (unichar uc = 0; uc < (0xFFFF); uc ++)
{
if ([characterSet characterIsMember:uc])
{
unicharBuffer[index] = uc;
index ++;
if (index == 20)
{
NSString * characters = [NSString stringWithCharacters:unicharBuffer length:index];
[toReturn appendString:characters];
index = 0;
}
}
}
if (index != 0)
{
NSString * characters = [NSString stringWithCharacters:unicharBuffer length:index];
[toReturn appendString:characters];
}
return toReturn;
}
First of all, you have to be careful about what you consider characters. The API of NSString uses the word characters when talking about what Unicode refers to as UTF-16 code units, but dealing with code units in isolation will not give you what users think of as characters. For example, there are combining characters that compose with the previous character to produce a different glyph. Also, there are surrogate pairs, which only make sense when, um, paired.
As a result, you will actually need to collect substrings which contain what the user thinks of as characters.
I was about to write code very similar to Grzegorz Krukowski's answer. He beat me to it, so I won't but I will add that your code to filter out the legal characters is broken because of the reasons I cite above. For example, if the text contains "é" and it's decomposed as "e" plus a combining acute accent, your code will strip the "e", leaving a dangling combining acute accent. I believe your intent is to treat the "é" as illegal.