how to convert NSString to NSArray [duplicate] - ios

This question already has answers here:
Comma-separated string to NSArray in Objective-C
(2 answers)
Closed 8 years ago.
I have a string like
NSString* str = #"[90, 5, 6]";
I need to convert it to an array like
NSArray * numbers = [90, 5 , 6];
I did a quite long way like this:
+ (NSArray*) stringToArray:(NSString*)str
{
NSString *sep = #"[,";
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:sep];
NSArray *temp=[str componentsSeparatedByCharactersInSet:set];
NSMutableArray* numbers = [[NSMutableArray alloc] init];
for (NSString* s in temp) {
NSNumber *n = [NSNumber numberWithInteger:[s integerValue]];
[numbers addObject:n];
}
return numbers;
}
Is there any neat and quick way to do such conversion?
Thanks

First remove the unwanted characters from the string, like white spaces and braces:
NSString* str = #"[90, 5, 6]";
NSCharacterSet* characterSet = [[NSCharacterSet
characterSetWithCharactersInString:#"0123456789,"] invertedSet];
NSString* newString = [[str componentsSeparatedByCharactersInSet:characterSet]
componentsJoinedByString:#""];
You will have a string like this: 90,5,6. Then simply split using the comma and convert to NSNumber:
NSArray* arrayOfStrings = [newString componentsSeparatedByString:#","];
NSMutableArray* arrayOfNumbers = [NSMutableArray arrayWithCapacity:arrayOfStrings.count];
for (NSString* string in arrayOfStrings) {
[arrayOfNumbers addObject:[NSDecimalNumber decimalNumberWithString:string]];
}
Using the NSString category from this response it can be simplified to:
NSArray* arrayOfStrings = [newString componentsSeparatedByString:#","];
NSArray* arrayOfNumbers = [arrayOfStrings valueForKey: #"decimalNumberValue"];

NSString* str = #"[90, 5, 6]";
NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:#"[] "];
NSArray *array = [[[str componentsSeparatedByCharactersInSet:characterSet]
componentsJoinedByString:#""]
componentsSeparatedByString:#","];

Try like this
NSArray *arr = [string componentsSeparatedByString:#","];

NSString *newSTR = [str stringByReplacingOccurrencesOfString:#"[" withString:#""];
newSTR = [newSTR stringByReplacingOccurrencesOfString:#"]" withString:#""];
NSArray *items = [newSTR componentsSeparatedByString:#","];

You can achieve that using regular expression 
([0-9]+)
NSError* error = nil;
NSString* str = #"[90, 5, 6]";
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:#"([0-9]+)" options:0 error:&error];
NSArray* matches = [regex matchesInString:str options:0 range:NSMakeRange(0, [str length])];
Then you have a NSArray of string, you just need to iterate it and convert the strings to number and insert them into an array.

Related

Use regular expression to find and replace the string from Textfield in NSString

I would like to use regular expression to find and replace the string. In my scenario {3} and {2} are UITextField tag values. Based on the tag value, I would like to replace the respective textfield values and calculate the string value using NSExpression.
Sample Input String :
NSString *cumputedValue = #"{3}*0.42/({2}/100)^2";
Note: The textFields are created dynamically based on JSON response.
I got the answer for this question. Here the computedString contains the value as "{3}*0.42/({2}/100)^2".
- (NSString *)autoCalculationField: (NSString *)computedString {
NSString *computedStringFormula = [NSString stringWithFormat:#"%#",computedString];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\\{(\\d+)\\}"
options:0
error:nil];
NSArray *matches = [regex matchesInString:computedStringFormula
options:0
range:NSMakeRange(0, computedStringFormula.length)];
NSString *expressionStr = computedStringFormula;
for (NSTextCheckingResult *r in matches)
{
NSRange numberRange = [r rangeAtIndex:1];
NSString *newString = [NSString stringWithFormat:#"%.2f",[self getInputFieldValue:[computedStringFormula substringWithRange:numberRange]]];
expressionStr = [expressionStr stringByReplacingOccurrencesOfString:[NSString stringWithFormat:#"{%#}",[computedStringFormula substringWithRange:numberRange]] withString:newString];
}
NSExpression *expression = [NSExpression expressionWithFormat:expressionStr];
return [expression expressionValueWithObject:nil context:nil];
}
- (float)getInputFieldValue: (NSString *)tagValue {
UITextField *tempTextFd = (UITextField *)[self.view viewWithTag:[tagValue intValue]];
return [tempTextFd.text floatValue];
}
You could save the textField tags in a NSDictionary with the value that they represent.
After that use stringByReplacingOccurrencesOfString to replace the values that you wish to.
Something like this:
for (NSString *key in dict) {
cumputedValue = [cumputedValue stringByReplacingOccurrencesOfString:[NSString stringWithFormat:#"{#%}", key] withString:[NSString stringWithFormat:#"%#", dict objectForKey:#key]];
}
This way you can have the values replaced

Objective-C: Convert String to integer separated by colon

i have string value
NSString *str = #"12:15"
now how to convert it in to integer value??
i tryNSInteger i =[str integerValue];
but it's return only 12 and i want 1215.
Please suggest.
Thank you
A more generic approach would be to replace everything but the numeric values with an empty string like below:
NSString *str = #"12: a15xx";
str = [str stringByReplacingOccurrencesOfString:#"[^0-9]"
withString:#""
options:NSRegularExpressionSearch
range:NSMakeRange(0, str.length)];
NSLog(#"%d", str.integerValue); // prints 1215
a simple answer would be
NSString *str=#"12:15";
str = [str stringByReplacingOccurrencesOfString:#":" withString:#""];
NSInteger i =[str integerValue];
NSArray* arr = [#"12:15" componentsSeparatedByString: #":"];
NSString* strValue = [NSString stringWithFormat:#"%#%#",[arr objectAtIndex:0],[arr objectAtIndex:1]];
int value=(int)strValue;

How to parse a NSString

The string is myAgent(9953593875).Amt:Rs.594 and want to extract 9953593875 from it. Here is what I tried:
NSRange range = [feDetails rangeOfString:#"."];
NSString *truncatedFeDetails = [feDetails substringWithRange:NSMakeRange(0, range.location)];
NSLog(#"truncatedString-->%#",truncatedFeDetails);
This outputs: truncatedString-->AmzAgent(9953593875)
Or you do like this:
NSString *string = #"myAgent(9953593875).Amt:Rs.594.";
NSRange rangeOne = [string rangeOfString:#"("];
NSRange rangeTwo = [string rangeOfString:#")"];
if (rangeOne.location != NSNotFound && rangeTwo.location != NSNotFound) {
NSString *truncatedFeDetails = [string substringWithRange:NSMakeRange(rangeOne.location + 1, rangeTwo.location - rangeOne.location - 1)];
NSLog(#"%#",truncatedFeDetails);
}
do like
Step-1
// split the string first based on .
for example
NSString *value = #"myAgent(9953593875).Amt:Rs.594.How I get 9953593875 only";
NSArray *arr = [value componentsSeparatedByString:#"."];
NSString * AmzAgent = [arr firstObject]; // or use [arr firstObject];
NSLog(#"with name ==%#",AmzAgent);
in here u get the output of myAgent(9953593875)
Step-2
in here use replace string like
AmzAgent = [AmzAgent stringByReplacingOccurrencesOfString:#"myAgent("
withString:#""];
AmzAgent = [AmzAgent stringByReplacingOccurrencesOfString:#")"
withString:#""];
NSLog(#"final ==%#",AmzAgent);
finally you get output as 9953593875
Try this
NSString *str = #"myAgent(9953593875).Amt:Rs.594.";
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"(?<=\\()\\d+(?=\\))"
options:NSRegularExpressionCaseInsensitive
error:nil];
NSString *result = [str substringWithRange:[regex firstMatchInString:str options:0 range:NSMakeRange(0, [str length])].range];
//result = 9953593875

Check if there is a word after a word (NSSTRING)

I have a fun little tricky problem. So I need to create an if statement that can detect if there is a word after a word in an array
so my code is
NSArray *words = [texfield.text componentsSeparatedByString:#" "];
int index = [words indexOfObject:#"string"];
I am not sure if I have to do something like
NSString*needle=words[index+1];
if (needle isEqualto #"") {
//There is a word after #"string";
}
What should I do?
How can I determine is there is a word after #"string"?
I appreciate all the help!! :)
Yeah, you have to:
NSArray *words = [texfield.text componentsSeparatedByString:#" "];
NSInteger index = [words indexOfObject:#"string"];
NSInteger afterIndex = index+1;
if(afterIndex<words.count) {
NSString *needle = words[index+1];
if (needle isEqualToString #"") {
//do something
}
}
NSString *yourString = #"string stackoverflow word after string regex";
NSRange yourStringRange = NSMakeRange(0, [yourString length]);
NSString *pattern = #"string\\s*([^\\s]*)";
NSError *error = nil;
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern: pattern options:0 error:&error];
NSArray* matches = [regex matchesInString:yourString options:0 range: yourStringRange];
for (NSTextCheckingResult* match in matches) {
NSRange rangeForMatch = [match rangeAtIndex:1];
NSLog(#"word after STRING: %#", [yourString substringWithRange:rangeForMatch]);
}
Output:
word after STRING: stackoverflow
word after STRING: regex
Method componentsSeparatedByString: will give all components separated by input NSString.
Your eg. NSArray *words = [texfield.text componentsSeparatedByString:#" "];
will have all string separated by " ". So just check if any
NSInteger afterIndex = index+1;
if(afterIndex<words.count) if Yes, you have NSStringavailable.

How to concatenate NSArray values by excluding brackets?

My array is like this
(1,2,3,)
(4,5,6,)
(7,8,9,)
I want to concatenate all these values i.e;123456789
I tried like this NSString *str5=[array componentsJoinedByString:#" "];
but I'm not getting the output.
can anyone provide me some information.
Looks like you have an NSArray of NSArray. First loop through the original NSArray and flatten it then apply componentsJoinedByString.
Create an NSMutableArray, loop through your original array and call addObjectsFromArray: with each subarray.
NSMutableArray *flattenArray = [[NSMutableArray alloc] init];
for(NSArray *array in originalArray)
{
[flattenArray addObjectsFromArray: array];
}
NSString *str5 = [flattenArray componentsJoinedByString:#" "];
This should work.
try like this it'l give expected output but i don't know is it efficient method or not ,
NSArray *arr=[[NSArray alloc]initWithObjects:#"(1,2,3)",#"(4,5,6)", nil];
NSString *str=[arr componentsJoinedByString:#""];
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:#",()"];
str = [[str componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: #""];
NSLog(#"%#",str);
Try this for Character replacing brackets with null values.
Code ::
NSArray *arr = [[NSArray alloc] initWithObjects:#"(1, 2, 3, )", #"(4, 5, 6, )", #"(7, 8, 9, )", nil];
for (int i = 0; i < [arr count]; i++) {
NSLog (#"==> %#", [or objectAtIndex:i]);
}
NSString *str5 = [arr componentsJoinedByString:#" "];
NSLog(#" ==> %#", str5);
str5 = [str5 stringByReplacingOccurrencesOfString:#"(" withString:#""];
str5 = [str5 stringByReplacingOccurrencesOfString:#" " withString:#""];
str5 = [str5 stringByReplacingOccurrencesOfString:#")" withString:#""];
str5 = [str5 stringByReplacingOccurrencesOfString:#"," withString:#""];
//Or Try this
NSCharacterSet *doNotWantChars = [NSCharacterSet characterSetWithCharactersInString:#",() "];
str5 = [[str5 componentsSeparatedByCharactersInSet: doNotWantChars] componentsJoinedByString: #""];
NSLog(#" ==> %#", str5);
NSLog(#"Output :: %#", str5);
I've replaced "(", ")", " " & "," with ""(null) values
Hopefully, it'll help you.Thanks.

Resources