make array out of string with variable number of spaces in Objective-C - 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"];

Related

Replace each word in a string with (the first letter + number of characters between + last letter)

I'm using objective-c to parse a sentence here:
NSString *myString = #“Some words to form a string”;
Here is what I have so far:
NSMutableString *firstCharacters = [NSMutableString string];
NSMutableString *lastCharacters = [myString substringFromIndex:[myString length] - 1]
NSArray *arrayOfWords = [myString componentsSeparatedByString:[NSCharacterSet whitespaceCharacterSet]];
for (NSString *word in arrayOfWords) {
if ([word length] > 0) {
NSString *firstLetter = [word substringToIndex:1];
[firstCharacters appendString:lastCharacters];
and then I am really stumped at this point. I want to NSLog the recombined string so that it looks like this:
"S2e w3s to f2m a s3g"
Please try following code :
NSString *myString = #"Some words to form a string";
NSArray *wordsInSentence = [myString componentsSeparatedByString:#" "];
NSMutableArray *expectedResultArray = [[NSMutableArray alloc] init];
for (NSString *word in wordsInSentence) {
NSString *finalExpectedString = word;
if (word.length > 2) {
NSString *firstLetterInWord = [word substringToIndex:1];
NSString *lastLetterInWord = [word substringFromIndex:[word length] - 1];
finalExpectedString = [NSString stringWithFormat:#"%#%d%#", firstLetterInWord, (int)word.length - 2, lastLetterInWord];
}
[expectedResultArray addObject:finalExpectedString];
}
NSString *printString = [expectedResultArray componentsJoinedByString:#" "];
NSLog(#"Result : %#", printString);

Is there a simple way to split a NSString into an array of characters?

Is there a simple way to split a NSString into an array of characters? It would actually be best if the resulting type were a collection of NSString's themselves, just one character each.
Yes, I know I can do this in a loop, but I'm wondering if there is a faster way to do this with any existing methods or functions the way you can with LINQ in C#.
e.g.
// I have this...
NSString * fooString = #"Hello";
// And want this...
NSArray * fooChars; // <-- Contains the NSStrings, #"H", #"e", #"l", #"l" and #"o"
You could do something like this (if you want to use enumerators)
NSString *fooString = #"Hello";
NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[fooString length]];
[fooString enumerateSubstringsInRange:NSMakeRange(0, fooString.length)
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[characters addObject:substring];
}];
And if you really wanted it in an NSArray finally
NSArray *fooChars = [NSArray arrayWithArray:characters];
Be sure to care about that some characters like emoji and others may span a longer range than just one index.
Here's a category method for NSString
#implementation (SplitString)
- (NSArray *)splitString
{
NSUInteger index = 0;
NSMutableArray *array = [NSMutableArray arrayWithCapacity:self.length];
while (index < self.length) {
NSRange range = [self rangeOfComposedCharacterSequenceAtIndex:index];
NSString *substring = [self substringWithRange:range];
[array addObject:substring];
index = range.location + range.length;
}
return array;
}
#end
convert it to NSData the [data bytes] will have a C string in the encoding that you pick [data length] bytes long.
Try this
NSMutableArray *array = [NSMutableArray array];
NSString *str = #"Hello";
for (int i = 0; i < [str length]; i++) {
NSString *ch = [str substringWithRange:NSMakeRange(i, 1)];
[array addObject:ch];
}

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

How to get values after "\n" character?

I want to take all values after a new line character \n from my string. How can I get those values?
Try this:
NSString *substring = nil;
NSRange newlineRange = [yourString rangeOfString:#"\n"];
if(newlineRange.location != NSNotFound) {
substring = [yourString substringFromIndex:newlineRange.location];
}
Take a look at method componentsSeparatedByString here.
A quick example taken from reference:
NSString *list = #"Norman, Stanley, Fletcher";
NSArray *listItems = [list componentsSeparatedByString:#", "];
this will produce a NSArray with strings separated: { #"Norman", #"Stanley", #"Fletcher" }
Here is similar function which splits the string by delimeter and return array with two trimmed values.
NSArray* splitStrByDelimAndTrim(NSString *string, NSString *delim)
{
NSRange range = [string rangeOfString: delim];
NSString *first;
NSString *second;
if(range.location == NSNotFound)
{
first = #"";
second = string;
}
else
{
first = [string substringToIndex: range.location];
first = [first stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
second = [string substringFromIndex: range.location + 1];
second = [second stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
}
return [NSArray arrayWithObjects: first, second, nil];
}

How to separate string by space using Objective-C?

Assume that I have a String like this:
hello world this may have lots of sp:ace or little space
I would like to seperate this String to this:
#"hello", #"world", #"this", #"may", #"have", #"lots", #"of", #"sp:ace", #"or", #"little", #"space"
Thank you.
NSString *aString = #"hello world this may have lots of sp:ace or little space";
NSArray *array = [aString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
array = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"SELF != ''"]];
I'd suggest a two-step aproach:
NSArray *wordsAndEmptyStrings = [yourLongString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSArray *words = [wordsAndEmptyStrings filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"length > 0"]];
This has worked for me
NSString * str = #"Hi Hello How Are You ?";
NSArray * arr = [str componentsSeparatedByString:#" "];
NSLog(#"Array values are : %#",arr);
It's very easy to do this with blocks, try something like this :
NSString* s = #"hello world this may have lots of space or little space";
NSMutableArray* ar = [NSMutableArray array];
[s enumerateSubstringsInRange:NSMakeRange(0, [s length]) options:NSStringEnumerationByWords usingBlock:^(NSString* word, NSRange wordRange, NSRange enclosingRange, BOOL* stop){
[ar addObject:word];
}];