How to separate string by space using Objective-C? - 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];
}];

Related

Split string into parts

I want to split NSString into array with fixed-length parts. How can i do this?
I searched about it, but i only find componentSeparatedByString method, but nothing more. It's also can be done manually, but is there a faster way to do this ?
Depends what you mean by "faster" - if it is processor performance you refer to, I'd guess that it is hard to beat substringWithRange:, but for robust, easy coding of a problem like this, regular expressions can actually come in quite handy.
Here's one that can be used to divide a string into 10-char chunks, allowing the last chunk to be of less than 10 chars:
NSString *pattern = #".{1,10}";
Unfortunately, the Cocoa implementation of the regex machinery is less elegant, but simple enough to use:
NSString *string = #"I want to split NSString into array with fixed-length parts. How can i do this?";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern: pattern options: 0 error: &error];
NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
NSMutableArray *result = [NSMutableArray array];
for (NSTextCheckingResult *match in matches) {
[result addObject: [string substringWithRange: match.range]];
}
Break the string into a sequence of NSRanges and then try using NSString's substringWithRange: method.
You can split a string in different ways.
One way is to split by spaces(or any character):
NSString *string = #"Hello World Obj C is Awesome";
NSArray *words = [string componentsSeparatedByString:#" "];
You can also split at exact points in a string:
NSString *word = [string substringWithRange:NSMakeRange(startPoint, FIXED_LENGTH)];
Simply put it in a loop for a fixed length and save to Mutable Array:
NSMutableArray *words = [NSMutableArray array];
for (int i = 0; i < [string length]; i++) {
NSString *word = [string substringWithRange:NSMakeRange(i, FIXED_LENGTH)]; //you may want to make #define
[array addObject:word];
}
Hope this helps.

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

Cocoa xcode4.3 hide characters of a string

I am adding string into a pickerView like this :
NSString *string = [NSString stringWithFormat:#"%# %#", xxx, xxx];
[pickerViewObjects addObject:string];
what i want to do is to hide the first part of the string, or of there's something to use like charachterAtIndex it will be useful because the first part of my string has a specific number of characters.
Use this method to get "(whitespaces) John"
NSString *string = #"Hello John";
NSUInteger spacePosition = [string rangeOfString:#" "].location;
NSMutableString *newString = [[NSMutableString alloc]init ];
for (int i=0; i<spacePosition; i++)
[newString appendString:#" "];
NSString *otherPartofString = [string substringFromIndex:(spacePosition)];
[newString appendString:otherPartofString];
NSLog(#"new String is '%#'",newString);
[newString release];
You can use [string substringWithRange:NSMakeRange(start, count)], that way you will only get a new string that you can use for displaying.
you can do like this:
find the position of space between two strings like this:
NSUInteger spacePosition = [string rangeOfString:#" "].location
then use:
NSString *otherPartofString = [string substringFromIndex:(spacePosition+1)];

Objective-C removing whitespace from strings in array

I want to import a file of strings line by line into an array. I want to get rid of all of the whitespace before and after the strings so that I can compare the strings a lot easier without having them not match due to small whitespace discrepancies. I NSData the content of the files then take the two strings
NSString* string = [[[NSString alloc] initWithBytes:[data bytes]
length:[data length]
encoding:NSUTF8StringEncoding] autorelease];
NSString* string2 = [[[NSString alloc] initWithBytes:[data2 bytes]
length:[data2 length]
encoding:NSUTF8StringEncoding] autorelease];
I tried below to remove the whitespace before adding to an array but it does not seem to work.
NSString *newString = [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
NSString *newString2 = [string2 stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
NSArray *fileInput = [newString componentsSeparatedByString:#"\n"];
NSArray *fileInput2 = [newString2 componentsSeparatedByString:#"\n"];
If you are looking at substituting all occurrences of whitespace then using stringByTrimmingCharactersInSet: won't help as it only trims off at the start and end of the string. You will need to use the stringByReplacingOccurrencesOfString:withString: method to eliminate the whitespace.
NSString * newString = [string stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString * newString2 = [string2 stringByReplacingOccurrencesOfString:#" " withString:#""];
However,
If you want to trim all the strings in the array then you will have to enumerate the array and add the trimmed strings in a new mutable array.
Looks to me like you are removing the white space from the front and back of the whole file but not from each line. Try something like this;
NSArray *fileInput2 = [newString2 componentsSeparatedByString:#"\n"];
NSMutableArray *trimmedFileInput2 = [NSMutableArray array];
for(NSString *gak in fileInput2) {
[trimmedFileInput2 addObject:[gak stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}
[Thanks #Deepak for the comment, dooh!]
Both #Deepak and #Bill Dudney being right, I'm just throwing in another way to solve your problem:
NSMutableArray *fileInput = [NSMutableArray array];
[string enumerateLinesUsingBlock:^(NSString *line, BOOL *stop) {
if ([line length] > 0) {
[fileInput addObject:
[line stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
}
}];
(Disclaimer: Works in iOS 4+, OS X 10.6+ only... but I love blocks! :))

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