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.
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.
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'v a string like - NSString * str = #"a. System discharges to the ground or to surface waters\n\nb. System causes sewage backup in structure\n\nc. “Black Soil” above system or drain field\n\n\nd. Ponding or puddles around tank, distribution boxes, or drain field" and want some specific substring from str for e.g. b. System causes sewage backup in structure
i have tried
NSRange r1 = [str rangeOfString:#"b. "];
NSString* substr = [str substringFromIndex:r1.location];
NSString* s1 = [substr stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
but i got whole string starting from b. System....
What i'm doing wrong?
Try something like:
NSRange r1 = [str rangeOfString:#"b. "];
NSString *substr = [str substringFromIndex:r1.location];
NSRange r2 = [substr rangeOfCharacterFromSet:[NSCharacterSet newlineCharacterSet]];
NSString *s1 = [substr substringToIndex:r2.location];
You have your starting point right but you also need to make it right at the end point. This code might help you. Though this mayn't be the exact thing that you might be looking for, it will surely help you in getting the desired result.
NSString *badStr = [NSString stringWithUTF8String:[response bytes]];
NSString *goodStr = [badStr substringFromIndex:76];
NSString *finalStr = [goodStr substringToIndex:[goodStr length]-9];
Basically, this code removes the unwanted characters from the beginning as well as from the ending of the string.
Hope this helps.
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.
I need to turn something like this
NSString *stringWithParentheses = #"This string uses (something special)";
Into this, programmatically.
NSString *normalString = #"This string uses";
The issue is I don't want to use all these weird libraries, regex, etc.
If you change your mind about the regex, here's a short, clean solution:
NSString *foo = #"First part (remove) (me (and ((me)))))) (and me) too))";
NSRegularExpression *expr = [NSRegularExpression regularExpressionWithPattern:#"\\(.*\\)" options:0 error:NULL];
NSString *bar = [expr stringByReplacingMatchesInString:foo options:0 range:NSMakeRange(0, foo.length) withTemplate:#""];
Everything between ( and ) gets removed, including any nested parentheses and unmatched parentheses within parentheses.
Just find the first open parentheses, note its index, find the closing one, note its index, and remove the characters between the indexes (including the indexes themselves).
To find the character use:
[string rangeOfString:#"("];
To remove a range:
[string stringByReplacingCharactersInRange:... withString:#""];
Here is a solution:
NSString* str = #"This string uses (something special)";
NSRange rgMin = [str rangeOfString:#"("];
NSRange rgMax = [str rangeOfString:#")"];
NSRange replaceRange = NSMakeRange(rgMin.location, rgMax.location-rgMin.location+1);
NSString* newString = str;
if (rgMin.location < rgMax.location)
{
newString = [str stringByReplacingCharactersInRange:replaceRange withString:#""];
}
It won't work on nested parentheses. Or multiple parentheses. But it works on your example. This is to be refined to your exact situation.
A way would be to find the position of the first occurrence of the '(' character and the last occurrence of the ')' character, and to build a substring by eliminating all the characters between these ranges. I've made an example:
NSString* str= #"This string uses (something special)";
NSRange r1=[str rangeOfString: #"("];
NSRange r2= [str rangeOfString: #")" options: NSBackwardsSearch];
NSLog(#"%#",[str stringByReplacingCharactersInRange: NSMakeRange(r1.location, r2.location+r2.length-r1.location) withString: #""]);