I have a string like #"(256) 435-8115" or #"256-435-81-15". I need only the digits (this is a phone number). Is this possible? I haven't found an NSString method to do that.
I think there is much simpler way:
-(NSString*)getNumbersFromString:(NSString*)String{
NSArray* Array = [String componentsSeparatedByCharactersInSet:
[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
NSString* returnString = [Array componentsJoinedByString:#""];
return (returnString);
}
Input:
NSString *stringWithPhoneNumber=#"(256) 435-8115";
NSArray *plainNumbersArray=
[stringWithPhoneNumber componentsSeparatedByCharactersInSet:
[[NSCharacterSet decimalDigitCharacterSet]invertedSet]];
NSString *plainNumbers = [plainNumbersArray componentsJoinedByString:#""];
NSLog(#"plain number is : %#",plainNumbers);
OutPut:
plain number is : 2564358115
You can use stringByReplacingOccurrencesOfString: withString: to remove characters you don't want such as #"(" with #""
Related
I want to remove only first space in below string.
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
Note: There is a space after IF_Distance and another space after
GET_Mi. I am unable to remove the space after IF_Distance.
Use rangeOfString: to locate the first space, then use stringByReplacingCharactersInRange:withString: to replace it with the empty string.
Remove space by using below code.
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *secondString = [str stringByReplacingOccurrencesOfString:#"IF_Distance " withString:#"IF_Distance"];
Try This:
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *firstStringContainingSpace = [[str componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] firstObject];//firstStringContainingSpace = IF_Distance
str = [str stringByReplacingCharactersInRange:[str rangeOfString:[NSString stringWithFormat:#"%# ",firstStringContainingSpace]] withString:firstStringContainingSpace];
Output:
str = #"IF_Distance(GET_Mi mi=km*1.4,STRING1,STRING2)";
You can remove first space by using following code:
First find space by using rangeOfString: and then remove by using stringByReplacingCharactersInRange:withString: method.
Like,
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *strSpace = #" ";
NSRange range = [str rangeOfString:strSpace];
NSString *strFinal;
if (NSNotFound != range.location) {
strFinal = [str stringByReplacingCharactersInRange:range withString:#""];
}
If you are looking for some more universal way - this is the variant of it:
- (NSString *)removeWhitespaces:(NSString *)string {
NSMutableArray * stringComponents = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] mutableCopy];
NSString * fStringComponent = [stringComponents firstObject];
[stringComponents removeObject:fStringComponent];
return [fStringComponent stringByAppendingString:[stringComponents componentsJoinedByString:#" "]];
}
I want to split the numbers and characters in a string only if a string contains numbers otherwise I don't want to split it.
ex:
String1 = #"hai 1234";
I want to split the this string as
String2 = 1234
String3 = hai;
another ex:
String1 = #"hai"
I don't want to split.
Use below code to split Characters & Numbers
//Numbers
NSString *numbers = [#"hai 1234" stringByTrimmingCharactersInSet:[NSCharacterSet letterCharacterSet]];
//Characters
NSString *characters = [#"hai 1234" stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
//number
NSString *onlyNumbers = [[string1 componentsSeparatedByCharactersInSet:
[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
componentsJoinedByString:#""];
//characters
NSString *onlyCharacters = [[string1 componentsSeparatedByCharactersInSet:
[[NSCharacterSet letterCharacterSet] invertedSet]] componentsJoinedByString:#""];
This question is a duplicate.
Objective-C: Find numbers in string
// Input
NSString *originalString = #"This is my string. #1234";
// Intermediate
NSString *numberString;
NSScanner *scanner = [NSScanner scannerWithString:originalString];
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];
// Text
NSString *text = [originalString stringByReplacingOccurrencesOfString:numberString withString:#""];
I want to import a file of strings line by line into an array. I want to get rid of all of the whitespace before and after the strings so that I can compare the strings a lot easier without having them not match due to small whitespace discrepancies. I NSData the content of the files then take the two strings
NSString* string = [[[NSString alloc] initWithBytes:[data bytes]
length:[data length]
encoding:NSUTF8StringEncoding] autorelease];
NSString* string2 = [[[NSString alloc] initWithBytes:[data2 bytes]
length:[data2 length]
encoding:NSUTF8StringEncoding] autorelease];
I tried below to remove the whitespace before adding to an array but it does not seem to work.
NSString *newString = [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
NSString *newString2 = [string2 stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
NSArray *fileInput = [newString componentsSeparatedByString:#"\n"];
NSArray *fileInput2 = [newString2 componentsSeparatedByString:#"\n"];
If you are looking at substituting all occurrences of whitespace then using stringByTrimmingCharactersInSet: won't help as it only trims off at the start and end of the string. You will need to use the stringByReplacingOccurrencesOfString:withString: method to eliminate the whitespace.
NSString * newString = [string stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString * newString2 = [string2 stringByReplacingOccurrencesOfString:#" " withString:#""];
However,
If you want to trim all the strings in the array then you will have to enumerate the array and add the trimmed strings in a new mutable array.
Looks to me like you are removing the white space from the front and back of the whole file but not from each line. Try something like this;
NSArray *fileInput2 = [newString2 componentsSeparatedByString:#"\n"];
NSMutableArray *trimmedFileInput2 = [NSMutableArray array];
for(NSString *gak in fileInput2) {
[trimmedFileInput2 addObject:[gak stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}
[Thanks #Deepak for the comment, dooh!]
Both #Deepak and #Bill Dudney being right, I'm just throwing in another way to solve your problem:
NSMutableArray *fileInput = [NSMutableArray array];
[string enumerateLinesUsingBlock:^(NSString *line, BOOL *stop) {
if ([line length] > 0) {
[fileInput addObject:
[line stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
}
}];
(Disclaimer: Works in iOS 4+, OS X 10.6+ only... but I love blocks! :))
I have the following string:
callback({"Outcome":"Success", "Message":null, "Identity":"Request", "Delay":0.002, "Symbol":"AAPL", "CompanyName":"Apple Inc.", "Date":"1\/13\/2011", "Time":"4:02:36 PM", "Open":344.6, "Close":345.93, "PreviousClose":344.42, "High":346.63, "Low":343.86, "Last":345.93, "Change":1.51, "PercentChange":0.438, "Volume":785960})
I want my final string to not contain callback( and the the last ) at the end of the string. How can I modify this NSString?
NSScanner is a good fit for this sort of thing.
NSString *json = nil;
NSScanner *scanner = [NSScanner scannerWithString:fullString];
[scanner scanUpToString:#"{" intoString:NULL]; // Scan to where the JSON begins
[scanner scanUpToString:#")" intoString:&json];
NSLog(#"json = %#", json);
Make an NSMutableString out of it, called string. i.e. NSMutableString *string = [NSMutableString stringWithString:myString];.
Then do string = [string substringToIndex:[string length]-1]; and then string = [string substringFromIndex:9]; or some such.
Or, again create an NSMutableString instance with your NSString instance, and call [string replaceOccurrencesOfString:#"callback(" withString:#"" options:NSLiteralSearch range:NSMakeRange(0, [string length])]; and [string replaceOccurrencesOfString:#")" withString:#"" options:NSLiteralSearch range:NSMakeRange(0, [string length])];. This might be preferred.
Either way, then create an NSString instance with the new string, something like goodString = [NSString stringWithString:string]; if you need an NSString out of this.
You can't modify an NSString (only an NSMutableString), but you can use [string substringWithRange:NSMakeRange(9, [string length] - 10)]. To actually mutate an NSMutableString, you'd have to use two deleteCharactersInRange: calls to trim the parts you don't want.
NSString *myString = #"A B C D E F G";
I want to remove the spaces, so the new string would be "ABCDEFG".
You could use:
NSString *stringWithoutSpaces = [myString
stringByReplacingOccurrencesOfString:#" " withString:#""];
If you want to support more than one space at a time, or support any whitespace, you can do this:
NSString* noSpaces =
[[myString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
componentsJoinedByString:#""];
Taken from NSString
stringByReplacingOccurrencesOfString:withString:
Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement
Parameters
target
The string to replace.
replacement
The string with which to replace target.
Return Value
A new string in which all occurrences of target in the receiver are replaced by replacement.
All above will works fine. But the right method is this:
yourString = [yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
It will work like a TRIM method. It will remove all front and back spaces.
Thanks
if the string is mutable, then you can transform it in place using this form:
[string replaceOccurrencesOfString:#" "
withString:#""
options:0
range:NSMakeRange(0, string.length)];
this is also useful if you would like the result to be a mutable instance of an input string:
NSMutableString * string = [concreteString mutableCopy];
[string replaceOccurrencesOfString:#" "
withString:#""
options:0
range:NSMakeRange(0, string.length)];
You can try this
- (NSString *)stripRemoveSpaceFrom:(NSString *)str {
while ([str rangeOfString:#" "].location != NSNotFound) {
str = [str stringByReplacingOccurrencesOfString:#" " withString:#""];
}
return str;
}
Hope this will help you out.