Split NSString to array by specific word - ios

I need to split NSString to array by specific word.
I've tried to use [componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#" "]]
But the split is performed by a single character, and I need a few chars.
Example:
NSString #"Hello great world";
Split key == #" great ";
result:
array[0] == #"Hello";
array[1] == #"world";

Try
NSString *str = #"Hello great world";
//you can use the bellow line to remove space
//str = [str stringByReplacingOccurrencesOfString:#" " withString:#""];
// split key = #"great"
NSArray *arr = [str componentsSeparatedByString:#"great"];

Code:
NSString *string = #"Hello great world";
NSArray *stringArray = [string componentsSeparatedByString: #" great "];
NSLog(#"Array 0: %#" [stringArray objectAtIndex:0]);
NSLog(#"Array 1: %#" [stringArray objectAtIndex:1]);

The easiest way is the following:
NSString *string = #"Hello Great World";
NSArray *stringArray = [string componentsSeparatedByString: #" "];
This can help you.

Related

How to replace \n with comma and remove the last \n ? - iOS Objective C

I want to display text which return from server in a label. Server return something like this *English\nMalay\nTamil\n*.
Currently I use:
stringByReplacingOccurrencesOfString:#"\n" withString:#", "
to replace the \n with comma. But how do I remove the last \n?
Now my text in the label shows:
"English, Malay, Tamil,"
I would like to get like
"English, Malay, Tamil"
Try like this way.
NSString *string = #"English\nMalay\nTamil\n";
//Make array from string
NSMutableArray *array = [NSMutableArray arrayWithArray:[string componentsSeparatedByString:#"\n"]];
//Remove all empty object from array
[array removeObject:#""];
//Join array object and make string
NSString *newString = [array componentsJoinedByString:#", "];
NSLog(#"%#",newString);
Why not remove last \n before making replacement by using substringToIndex?
NSString *mString = #"English\nMalay\nTamil\n";
NSLog(#"mString===before===%#", mString);
mString = [mString substringToIndex:mString.length-1];
mString = [mString stringByReplacingOccurrencesOfString:#"\n" withString:#", "];
NSLog(#"mString===after===%#", mString);
Output
mString===before===English
Malay
Tamil
mString===after===English, Malay, Tamil
You can do this by using below code
NSString *string=#"English\nMalay\nTamil\n";
NSMutableArray *arryLanguagge = [[string componentsSeparatedByString: #"\n"] mutableCopy];
[arryLanguagge removeObject:#""];
NSString *strLanguaage=[arryLanguagge componentsJoinedByString:#","];
NSLog(#"%#",strLanguaage);

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 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.

I have a NSString like this: "Firstname Lastname". How do I convert it to "Firstname L."?

I would like to change it to first name and last initial.
Thanks!
NSString* nameStr = #"Firstname Lastname";
NSArray* firstLastStrings = [nameStr componentsSeparatedByString:#" "];
NSString* firstName = [firstLastStrings objectAtIndex:0];
NSString* lastName = [firstLastStrings objectAtIndex:1];
char lastInitialChar = [lastName characterAtIndex:0];
NSString* newNameStr = [NSString stringWithFormat:#"%# %c.", firstName, lastInitialChar];
This could be much more concise, but I wanted clarity for the OP :) Hence all the interim variables and var names.
This would do it:
NSArray *components = [fullname componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSString *firstnameAndLastnameInitial = [NSString stringWithFormat:#"%# %#.", [components objectAtIndex:0], [[components objectAtIndex:1] substringToIndex:1]];
This assumes that fullname is an instance of NSString and contains two components separated by whitespace, so you will need to check for that as well.
You can use this code snippet, first separate string using componentsSeparatedByString, then join them again but only get the first character of Lastname
NSString *str = #"Firstname Lastname";
NSArray *arr = [str componentsSeparatedByString:#" "];
NSString *newString = [NSString stringWithFormat:#"%# %#.", [arr objectAtIndex:0], [[arr objectAtIndex:1] substringToIndex:1]];
Get an array of the parts of the name individually:
NSString *sourceName = ...whatever...;
NSArray *nameComponents =
[sourceName
componentsSeparatedByCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
Then, I guess:
NSString *compactName =
[NSString stringWithFormat:#"%# %#.",
[nameComponents objectAtIndex:0],
[[nameComponents lastObject] substringToIndex:1]];
That'll skip any middle names, though if there's only one name, like say 'Jeffry' then it'll output 'Jeffry J.'. If you pass in the empty string then it'll raise an exception when you attempt to get objectAtIndex:0 since that array will be empty. So you should check [nameComponents count].

iOS - parse a string using whitespace

I am an iOS newbie, so please pardon me if this is a beginner level question.
I have a string "hu_HU Hungary:Hungarian" and I want to put it into an array like {"hu", "HU", "Hungary:Hungarian"}. How would I parse it to remove the whitespace and then the underscore?
Use componentsSeparatedByCharactersInSet: method of NSString
To get the desired effect you must change the '_' to a ' ' or vice versa. Then you can use componentsSeparatedByString, like so:
NSString *source = #"hu_HU Hungary:Hungarian";
source = [source stringByReplacingOccurrencesOfString:#"_" withString:#" "];
NSArray *components = [source componentsSeparatedByString:#" "];
NSLog(#"%#",components);
NSString *theStr = #"hu_HU Hungary:Hungarian";
NSArray *pieces = [theStr componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString: #"_ "]];
//pieces = {"hu", "HU", "Hungary:Hungarian"}
pieces = [theStr componentsSeparatedByCharactersInSet: [[NSCharacterSet alphanumericCharacterSet] invertedSet]];
//pieces = {"hu", "HU", "Hungary", "Hungarian"}
//the motivation for this is a better defined set of non-alphanumeric characters
Here you are:
NSString *myString = #"hu_HU Hungary:Hungarian";
myString = [myString stringByReplacingOccurrencesOfString:#"_" withString:#" "];
NSArray *myArray = [myString componentsSeparatedByString:#" "];
All of these answers share an annoying problem. They assume that the items are separated by one and only one space.
NSString *theStr = #"hu_HU Hungary:Hungarian";
NSArray *pieces = [theStr componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString: #"_ "]];
//pieces = {"hu", "HU", "Hungary:Hungarian"}
NSString *theStr = #"hu_HU Hungary:Hungarian"; // note extra space
NSArray *pieces = [theStr componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString: #"_ "]];
//pieces = {"hu", "HU", " ", "Hungary:Hungarian"}

Resources