Split NSString from first whitespace - ios

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.

Related

Fetching data from SQLite and want to get only the last value of column id

I am fetching data from SQLite and want to get only the last value of column id in XCode.The code is
NSString *selquery = #"select id from watchlists";
if (self.uid != nil) {
self.uid = nil;
}
self.uid = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:selquery]];
NSString *valvar;
valvar = [_uid lastObject];
NSNumber *custval = [_uid valueForKey: #"#lastObject"];
NSString *imgval1 = [NSString stringWithFormat:#"%#_%s",custval,"1"];
NSLog(#"%#", imgval1);
Please tell me how can I get only the value because by using the above code I am getting array with last value of id.
I think this your case, try this it maybe help you
NSArray *temp=[NSArray arrayWithObjects:#"1",#"2",#"3", nil];
NSArray *temp0ne=[[NSArray alloc]initWithArray:temp];
// NSString *tmmp=[temp0ne lastObject];
NSArray *finalStr=[uid lastObject];
NSLog(#"Dictionary is---->%#",[finalStr lastObject]);
Output:
3_1
EDIT
NSArray *temp=[NSArray arrayWithObjects:#"(1)",#"(2)",#"(3)", nil];
NSArray *temp0ne=[[NSArray alloc]initWithArray:temp];
NSString *tmmp=[temp0ne lastObject];
NSString *final=[tmmp stringByReplacingOccurrencesOfString:#"(" withString:#""];
final=[final stringByReplacingOccurrencesOfString:#")" withString:#""];
NSString *imgval1 = [NSString stringWithFormat:#"%#_%s",final,"1"];
NSLog(#"%#", imgval1);
I don't know is this correct way or not try this....otherwise have look this link
I don't fully understand your code structure hehe. Try this:
NSString *selquery = #"select id from watchlists";
if (self.uid != nil) {
self.uid = nil;
}
self.uid = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:selquery]];
NSNumber *custval = [_uid objectAtIndex:[_uid count]-1];
*
NSString *str = [NSString stringWithFormat#"%#",custval];
str = [str stringByReplacingOccurrencesOfString:#"("
withString:#""];
NSString *finalCustval = [NSString stringWithFormat#"%#",str];
finalCustval = [finalCustval stringByReplacingOccurrencesOfString:#")"
withString:#""];
*
NSString *imgval1 = [NSString stringWithFormat:#"%#_%s",finalCustval ,"1"];
NSLog(#"%#", imgval1);
UPDATE
try adding the ones with *.

Parse all integers from string in Objective-C

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);
}
}

Unable to extracting a substring from an NSString

I have an input string in the format
"Jerry Lane"(angle bracket)jerry.lane#gmail.com(bracket closed),"Harry Potter"(angle bracket)harry.potter#gmail.com(bracket closed),"Indiana Jones",(angle bracket)indiana.jones#gmail.com(bracket closed),"Tom Cruise"(angle bracket)tom.cruise#gmail.com(bracket closed)
Here, i am supposed to first separate the string on the basis of comma delimiter, which would give me a separate string like
"Jerry Lane"(angle bracket)jerry.lane#gmail.com(bracket closed)
Then i need to save extract the string between the <> brackets, which is essentially the string "jerry.lane#gmail.com". I am using the following code, but it is giving me the following error:
Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFConstantString substringWithRange:]: Range or index out of bounds'
-(NSArray *)parseString:(NSString *)string
{
if(string)
{
NSArray *myArray = [string componentsSeparatedByString:#","];
for(NSMutableString *myString in myArray)
{
NSRange start,end;
start = [myString rangeOfString:#"<"];
end = [myString rangeOfString:#">"];
if(start.location != NSNotFound && end.location != NSNotFound)
{
NSString *emailAddress = [myString substringWithRange:NSMakeRange(start.location,end.location)];
NSString *name = [myString substringToIndex:start.location];
NSDictionary *myDictionary = [[NSDictionary alloc] init];
[myDictionary setValue:emailAddress forKey:#"Dhruvil Vyas"];
[testArray addObject:myDictionary];
}
}
}
return testArray;
}
The arguments that substring takes are the start position and the length
Not the start position and the end position.
More Info
borrrden's answer is correct. Here is another way to do this.
-(NSArray *)parseString:(NSString *)string
{
if(string)
{
NSArray *myArray = [string componentsSeparatedByString:#","];
for(NSMutableString *myString in myArray)
{
NSArray *tempNameArray = [myString componentsSeparatedByString:#"<"];
NSString *email = [tempNameArray objectAtIndex:1];
NSArray *tempMailArray = [email componentsSeparatedByString:#">"];
NSString *emailAddress = [tempMailArray objectAtIndex:0];
NSString *name = [tempNameArray objectAtIndex:0];
NSDictionary *myDictionary = [[NSDictionary alloc] init];
[myDictionary setValue:emailAddress forKey:#"Dhruvil Vyas"];
[testArray addObject:myDictionary];
}
}
return testArray;
}

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

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