Parse all integers from string in Objective-C - ios

I have a problem how to get all integer values from string in Objective-C
NSString *numbers = #"1, 2";
int number = [numbers intValue];
But this just takes the first number (1) but I need both of them.
Thank you guys.

Try something like this:
NSArray *listOfNumbers = [numbers componentsSeparatedByString:#","];
for (NSString *numberAsString in listOfNumbers) {
int number = [numberAsString intValue]; // you might want to trim the string first
}

This is for if they're always separated by a ", ":
NSString *numbers = #"1, 2";
NSArray *numberTokens = [numbers componentsSeparatedByString:#", "];
for (NSString *token in numberTokens) {
NSLog(#"%i", token.integerValue);
}
This solution allows you to specify multiple characters that might separate the numbers:
NSString *numbers = #"1, 2";
NSArray *numberTokens = [numbers componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#", "]];
for (NSString *token in numberTokens) {
if (token.length > 0) {
NSLog(#"%#: %i", token, token.integerValue);
}
}

Related

Changing NSString value (displayed as number) to two decimal places and make a percentage

When I retrieve my JSONResponse i retrieve a number that appears as 0.2434309606330154. This is the number I want, however it isn't in the format that I want. It is set up in a way that with three other response it equals to 1.
I've tried converting it to an NSNumber but it didn't work.
NSDictionary *parameters = #{
#"data": text.text,
};
NSMutableString *parameterString = [NSMutableString string];
for (NSString *key in [parameters allKeys]) {
if ([parameterString length]) {
[parameterString appendString:#"&"];
}
[parameterString appendFormat:#"%#=%#", key, parameters[key]];
}
NSLog(#"A: %#", jsonResponse[#"results"][#"A"]);
ALabel.text = [NSString stringWithFormat:#"%#",jsonResponse[#"results"][#"A"]];
NSString *string = [NSString stringWithFormat:#"%#",jsonResponse[#"results"][#"A"]];
CGFloat float = [string floatValue];
ALabel.text = [NSString stringWithFormat:#"%.02f",float];
In Swift 1.2:
self.ALabel?.text = NSString(format: "%.02f%%", string.floatValue) as String
NSString *string = [NSString stringWithFormat:#"%#",jsonResponse[#"results"][#"A"]];
ALabel.text = [NSString stringWithFormat:#"%.02f%%",string.floatValue];
Here output will be - 0.24%

In objective-c how to get characters after n-th?

I have a number which will be represented as string. It is longer than 4 chars. I need to create new string from 5th till the end for that number.
For example if I have 56789623, I need to have 9623 as a result (5678 | 9623).
How to do that?
P.S. I suppose that this is very simple question, but I don't know how properly ask Google about that.
NSString *str = #"56789623";
NSString *first, *second;
if ([str length] > 4) {
first = [str substringWithRange:NSMakeRange(0, 4)];
second = [str substringWithRange:NSMakeRange(4, [str length] - 4)];
} else {
first = str;
second = nil;
}
Use this Simple functions
- (NSString *)substringFromIndex:(NSUInteger)from;
- (NSString *)substringToIndex:(NSUInteger)to;
- (NSString *)substringWithRange:(NSRange)range;
You can use:
- (NSString *)substringFromIndex:(NSUInteger)anIndex
NSString *number = #"56789623";
NSString *result = [number substringFromIndex:4];
NSLog(#"%#", result);
result contains the string: #"9623"
The keywords you were looking for are: substring and range. There are several ways to use them. Example code split string into 2 equal (if number of characters is even almost equal) substrings:
NSString *str = #"56789623";
NSInteger middleIndex = (NSInteger)(str.length/2);
NSString *strFirstPart = [str substringToIndex:middleIndex];
NSString *strSecondPart = [str substringFromIndex:middleIndex];
NSString *strFirstPart2 = [str substringWithRange:NSMakeRange(0, middleIndex)];
NSString *strSecondPart2 = [str substringWithRange:NSMakeRange(middleIndex, [str length]-middleIndex)];

Split NSString from first whitespace

I have a name textfield in my app, where both the firstname maybe a middle and a lastname is written. Now I want to split these components by the first whitespace, the space between the firstname and the middlename/lastname, so I can put it into my model.
For example:
Textfield Text: John D. Sowers
String 1: John
String 2: D. Sowers.
I have tried using [[self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] firstObject]; & [[self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] lastObject];
But these only work if have a name without a middlename. Since it gets the first and the last object, and the middlename is ignored.
So how would I manage to accomplish what I want?
/*fullNameString is an NSString*/
NSRange rangeOfSpace = [fullNameString rangeOfString:#" "];
NSString *first = rangeOfSpace.location == NSNotFound ? fullNameString : [fullNameString substringToIndex:rangeOfSpace.location];
NSString *last = rangeOfSpace.location == NSNotFound ? nil :[fullNameString substringFromIndex:rangeOfSpace.location + 1];
...the conditional assignment (rangeOfSpace.location == NSNotFound ? <<default value>> : <<real first/last name>>) protects against an index out of bounds error.
Well that method is giving you an array with all the words split by white space, so then you can grab the first object as the first name and the rest of the objects as middle/last/etc
NSArray *ar = [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSString *firstName = [ar firstObject];
NSMutableString *rest = [[NSMutableString alloc] init];
for(int i = 1; i < ar.count; i++)
{
[rest appendString:[ar objectAtIndex:i]];
[rest appendString:#" "];
}
//now first name has the first name
//rest has the rest
There might be easier way to do this, but this is one way..
Hope it helps
Daniel
I think this example below I did, solves your problem.
Remember you can assign values from the array directly, without transforming into string.
Here is an example:
NSString *textField = #"John D. Sowers";
NSArray *fullName = [textField componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#" "]];
if (fullName.count)
{
if (fullName.count > 2)
{
NSLog(#"Array has more than 2 objects");
NSString *name = fullName[0];
NSLog(#"Name:%#",name);
NSString *middleName = fullName[1];
NSLog(#"Middle Name:%#",middleName);
NSString *lastName = fullName[2];
NSLog(#"Last Name:%#",lastName);
}
else if(fullName.count == 2)
{
NSLog(#"Array has 2 objects");
NSString *name = fullName[0];
NSLog(#"Name:%#",name);
NSString *lastName = fullName[1];
NSLog(#"Last Name:%#",lastName);
}
else
{
NSString *name = fullName[0];
}
}
I found this to be most robust:
NSString *fullNameString = #"\n Barnaby Marmaduke \n \n Aloysius ";
NSMutableArray *nameArray = [[fullNameString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] mutableCopy];
[nameArray removeObject:#""];
NSString *firstName = [nameArray firstObject];
if(nameArray.count)
{
[nameArray removeObjectAtIndex:0];
}
NSString *nameRemainder = [nameArray componentsJoinedByString:#" "];
Bob's your uncle.

NSSet to string separaing by comma

I have the next code for converting NSSet to string separating by comma:
-(NSString *)toStringSeparatingByComma
{
NSMutableString *resultString = [NSMutableString new];
NSEnumerator *enumerator = [self objectEnumerator];
NSString* value;
while ((value = [enumerator nextObject])) {
[resultString appendFormat:[NSString stringWithFormat:#" %# ,",value]];//1
}
NSRange lastComma = [resultString rangeOfString:#"," options:NSBackwardsSearch];
if(lastComma.location != NSNotFound) {
resultString = [resultString stringByReplacingCharactersInRange:lastComma //2
withString: #""];
}
return resultString;
}
It seems that it works, but I get here two warnings:
1. format string is not a string literal (potentially insecure)
2. incompatible pointer types assigning to nsmutablestring from nsstring
How to rewrite it to avoid of warnings?
There is another way to achieve what you are trying to do with fewer lines of code:
You can get an array of NSSet objects using:
NSArray *myArray = [mySet allObjects];
You can convert the array to a string:
NSString *myStr = [myArray componentsJoinedByString:#","];
stringByReplacingCharactersInRange method's return type NSString. You are assigning it to NSMutableString. Use mutable copy.
resultString = [[resultString stringByReplacingCharactersInRange:lastComma //2
withString: #""]mutablecopy]

Getting a string in textfield before a specific string in the textfield

So my textfield has the following text. #"A big Tomato is red."
I want to get the word before "is".
When I type
NSString *someString = [[textfield componentsSeparatedByString:#"is"]objectAtIndex:0];
I always get "A big Tomato" instead of just "Tomato". In the app people will type things before "is" so I need to always get the string before "is". I would appreciate any help I can get. *Warning,
This is a very difficult problem.
Try this,
NSString *value = #"A big Tomato is red.";
NSArray *array = [value componentsSeparatedByString:#" "];
if ([array containsObject:#"is"]) {
NSInteger index = [array indexOfObject:#"is"];
if (index != 0) {
NSString *word = [array objectAtIndex:index - 1];
NSLog(#"%#", word);
}
}
Try this
NSString *string = #"A big Tomato is red.";
if ([string rangeOfString:#"is"].location == NSNotFound) {
NSLog(#"string does not contain is");
} else {
NSLog(#"string contains is!");
}
try this
NSString *str = #"A big tomato is red";
NSArray *arr = [str componentsSeparatedByString:#" "];
int index = [arr indexOfObject:#"is"];
if(index > 1)
NSString *str_tomato = arr[index-1];
else
//"is" is the first word of sentence
as per yvesleborg's comment

Resources