Split the Numbers and characters in the String - objective-c

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:#""];

Related

Add 1 to a number in an NSString that contains characters Objective-C

I am new to learning Objective-C (my first programming language!) and trying to write a little program that will add 1 to a number contained within a string. E.g. AA1BB becomes AA2BB.
.
So far I have tried to extract the number and add 1. Then extract the letters and add everything back together in a new string. I have had some success but can't manage to get back to the original arrangement of the initial string.
The code I have so far gives a result of 2BB and disregards the characters before the number which is not what I am after (the result I am trying for with this example would be AA2BB). I can't figure out why!
NSString* aString = #"AA1BB";
NSCharacterSet *numberCharset = [NSCharacterSet characterSetWithCharactersInString:#"0123456789-"]; //Creating a set of Characters object//
NSScanner *theScanner = [NSScanner scannerWithString:aString];
int someNumbers = 0;
while (![theScanner isAtEnd]) {
// Remove Letters
[theScanner scanUpToCharactersFromSet:numberCharset
intoString:NULL];
if ([theScanner scanInt:&someNumbers]) {}
}
NSCharacterSet *letterCharset = [NSCharacterSet characterSetWithCharactersInString:#"ABCDEFGHIJKLMNOPQRSTUVWXYZ"];
NSScanner *letterScanner = [NSScanner scannerWithString:aString];
NSString* someLetters;
while (![letterScanner isAtEnd]) {
// Remove numbers
[letterScanner scanUpToCharactersFromSet:letterCharset
intoString:NULL];
if ([letterScanner scanCharactersFromSet:letterCharset intoString:&someLetters]) {}
}
++someNumbers; //adds +1 to the Number//
NSString *newString = [[NSString alloc]initWithFormat:#"%i%#", someNumbers, someLetters];
NSLog (#"String is now %#", newString);
This is an alternative solution with Regular Expression.
It finds the range of the integer (\\d+ is one or more digits), extracts it, increments it and replaces the value at the given range.
NSString* aString = #"AA1BB";
NSRange range = [aString rangeOfString:#"\\d+" options:NSRegularExpressionSearch];
if (range.location != NSNotFound) {
NSInteger numericValue = [aString substringWithRange:range].integerValue;
numericValue++;
aString = [aString stringByReplacingCharactersInRange:range withString:[NSString stringWithFormat:#"%ld", numericValue]];
}
NSLog(#"%#", aString);

Obj-C: Create Array From String Where items are in <>

I am trying to parse a String to an Array each item is between <> for example <this is column 1><this is column 2> etc....
Help would be much appreciated.
Thanks
Something to demonstrate:
NSString *string = #"<this is column 1><this is column 2>";
NSScanner *scanner = [NSScanner scannerWithString:string];
NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
NSString *temp;
while ([scanner isAtEnd] == NO)
{
// Disregard the result of the scanner because it returns NO if the
// "up to" string is the first one it encounters.
// You should still have this in case there are other characters
// between the right and left angle brackets.
(void) [scanner scanUpToString:#"<" intoString:NULL];
// Scan the left angle bracket to move the scanner location past it.
(void) [scanner scanString:#"<" intoString:NULL];
// Attempt to get the string.
BOOL success = [scanner scanUpToString:#">" intoString:&temp];
// Scan the right angle bracket to move the scanner location past it.
(void) [scanner scanString:#">" intoString:NULL];
if (success == YES)
{
[array addObject:temp];
}
}
NSLog(#"%#", array);
NSString *input =#"<one><two><three>";
NSString *strippedInput = [input stringByReplacingOccurencesOfString: #">" withString: #""]; //strips all > from input string
NSArray *array = [strippedInput componentsSeperatedByString:#"<"];
Note that [array objectAtIndex:0] will be an empty string ("") an this doesn't work of course, if one of the "actual" string contain < or >
One approach might be to use either componentsSeparatedByCharactersInSet or componentsSeparatedByString from NSString.
NSString *test = #"<one> <two> <three>";
NSArray *array1 = [test componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"<>"]];
NSArray *array2 = [test componentsSeparatedByString:#"<"];
You'll need to do some cleaning up afterward, either trimming in the case of array2 or removing white-space strings in the case of array1

Getting digits from an NSString

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 #""

How can I parse this string using NSString?

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.

make array out of string with variable number of spaces in Objective-C

This is the code that I would use if it was always single spaces in between words. Since I have multiple spaces in between some words how can my code be changed to remove the extra spaces when using componentsSeparatedBySring. I'm new to OBjective-C so any help would be greatly appreciated!
Here is my code:
NSString *myString = #"One Two Three Four Five";
NSArray *myArray = [myString componentsSeparatedByString: #" "];
Use NSScanner instead:
NSMutableArray *results = [NSMutableArray array];
NSScanner *scanner = [NSScanner scannerWithString:input];
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:#" "];
while ([scanner isAtEnd] == NO)
{
NSString *string;
[scanner scanUpToCharactersFromSet:charSet intoString:&string];
[results addObject:string];
}
+ (NSArray *)componentsInString:(NSString *)string withSeparacterInString:(NSString *)separaterStr
{
if (!string || !separaterStr || [separaterStr length] < 1)
return [NSArray array];
NSMutableArray *arr = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:separaterStr]] mutableCopy];
[arr removeObject:#""]; // removes all empty components
return arr;
}
NSArray *arr = [Utils componentsInString:#"12 123 \n 14 " withSeparacterInString:#" \n"];