how to remove spaces, brackets and " from nsarray - objective-c

I have an array where i am trying to remove the access spaces, brackets and " from the nsarray in order to use componentsSeparatedByString:#";"
NSArray *paths = [dic valueForKey:#"PATH"];
for(NSString *s in paths)
{
NSLog(#"String: %#", s);
}
String: (
"29858,39812;29856,39812;29800,39819;29668,39843;29650,39847;29613,39855;29613,39855;29613,39856;29605,39857;29603,39867;29603,39867;29599,39892;29596,39909;29587,39957;29571,40018;29563,40038;29560,40043"
)
this is the output give as show there are spaces, brackets and " how could i remove them
?
As this line is juz a string inside that array "29858,39812;29856,39812;29800,39819;29668,39843;29650,39847;29613,39855;29613,‌​39855;29613,39856;29605,39857;29603,39867;29603,39867;29599,39892;29596,39909;295‌​87,39957;29571,40018;29563,40038;29560,40043" this line is a string inside the path array and i try using componentsSeparatedByString:#";" it could not be spilt all there are spaces brackets and " inside.

Try stringByTrimmingCharactersInSet:
NSCharacterSet *charsToTrim = [NSCharacterSet characterSetWithCharactersInString:#"() \n\""];
s = [s stringByTrimmingCharactersInSet:charsToTrim];

try to use:
s = [s stringByReplacingOccurrencesOfString:#";"
withString:#""];

it separates the numbers for you and you can work with them as i.e. NSInteger values.
NSString *_inputString = #"29858,39812;29856,39812;29800,39819;29668,39843;29650,39847;29613,39855;29613,39855;29613,39856;29605,39857;29603,39867;29603,39867;29599,39892;29596,39909;29587,39957;29571,40018;29563,40038;29560,40043";
NSString *_setCommonSeparator = [_inputString stringByReplacingOccurrencesOfString:#";" withString:#","];
NSArray *_separetedNumbers = [_setCommonSeparator componentsSeparatedByString:#","];
for (NSString *_currentNumber in _separetedNumbers) {
NSInteger _integer = [_currentNumber integerValue];
NSLog(#"number : %d", _integer);
}

Related

How to remove the first space from the NSString?

I want to remove only first space in below string.
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
Note: There is a space after IF_Distance and another space after
GET_Mi. I am unable to remove the space after IF_Distance.
Use rangeOfString: to locate the first space, then use stringByReplacingCharactersInRange:withString: to replace it with the empty string.
Remove space by using below code.
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *secondString = [str stringByReplacingOccurrencesOfString:#"IF_Distance " withString:#"IF_Distance"];
Try This:
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *firstStringContainingSpace = [[str componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] firstObject];//firstStringContainingSpace = IF_Distance
str = [str stringByReplacingCharactersInRange:[str rangeOfString:[NSString stringWithFormat:#"%# ",firstStringContainingSpace]] withString:firstStringContainingSpace];
Output:
str = #"IF_Distance(GET_Mi mi=km*1.4,STRING1,STRING2)";
You can remove first space by using following code:
First find space by using rangeOfString: and then remove by using stringByReplacingCharactersInRange:withString: method.
Like,
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *strSpace = #" ";
NSRange range = [str rangeOfString:strSpace];
NSString *strFinal;
if (NSNotFound != range.location) {
strFinal = [str stringByReplacingCharactersInRange:range withString:#""];
}
If you are looking for some more universal way - this is the variant of it:
- (NSString *)removeWhitespaces:(NSString *)string {
NSMutableArray * stringComponents = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] mutableCopy];
NSString * fStringComponent = [stringComponents firstObject];
[stringComponents removeObject:fStringComponent];
return [fStringComponent stringByAppendingString:[stringComponents componentsJoinedByString:#" "]];
}

split NSString using componentsSeparatedByString

I have a string I need to split. It would be easy using componentsSeparatedByString but my problem is that the separator is a comma but I could have commas that aren't separator.
I explain:
My string:
NSString *str = #"black,red, blue,yellow";
the comma between red and blue must not be considered as separator.
I can determine if comma is a separator or not checking if after it there is a white space.
The goal is to obtain an array with:
(
black,
"red, blue",
yellow
)
This is tricky. First replace all occurences of ', ' (comma+space) with say '|' then use components separated method. Once you are done, again replace '|' with ', ' (comma+space).
Just to complete the picture, a solution that uses a regular expression to directly identify commas not followed by white space, as you explain in your question.
As others have suggested, use this pattern to substitute with a temporary separator string and split by that.
NSString *pattern = #",(?!\\s)"; // Match a comma not followed by white space.
NSString *tempSeparator = #"SomeTempSeparatorString"; // You can also just use "|", as long as you are sure it is not in your input.
// Now replace the single commas but not the ones you want to keep
NSString *cleanedStr = [str stringByReplacingOccurrencesOfString: pattern
withString: tempSeparator
options: NSRegularExpressionSearch
range: NSMakeRange(0, str.length)];
// Now all that is needed is to split the string
NSArray *result = [cleanedStr componentsSeparatedByString: tempSeparator];
If you are not familiar with the regex pattern used, the (?!\\s) is a negative lookahead, which you can find explained quite well, for instance here.
Here is coding implementation for cronyneaus4u's solution:
NSString *str = #"black,red, blue,yellow";
str = [str stringByReplacingOccurrencesOfString:#", " withString:#"|"];
NSArray *wordArray = [str componentsSeparatedByString:#","];
NSMutableArray *finalArray = [NSMutableArray array];
for (NSString *str in wordArray)
{
str = [str stringByReplacingOccurrencesOfString:#"|" withString:#", "];
[finalArray addObject:str];
}
NSLog(#"finalArray = %#", finalArray);
NSString *str = #"black,red, blue,yellow";
NSArray *array = [str componentsSeparatedByString:#","];
NSMutableArray *finalArray = [[NSMutableArray alloc] init];
for (int i=0; i < [array count]; i++) {
NSString *str1 = [array objectAtIndex:i];
if ([[str1 substringToIndex:1] isEqualToString:#" "]) {
NSString *str2 = [finalArray objectAtIndex:(i-1)];
str2 = [NSString stringWithFormat:#"%#,%#",str2,str1];
[finalArray replaceObjectAtIndex:(i-1) withObject:str2];
}
else {
[finalArray addObject:str1];
}
}
NSLog(#"final array count : %d description : %#",[finalArray count],[finalArray description]);
Output:
final array count : 3 description : (
black,
"red, blue",
yellow
)

How to parse a string format like [***]***?

I need to parse a string like [abc]000, and what I want to get is an array containing abc and 000. Is there an easy way to do it?
I'm using code like this:
NSString *sampleString = #"[abc]000";
NSArray *sampleParts = [sampleString componentsSeparatedByString:#"]"];
NSString *firstPart = [[[sampleParts objectAtIndex:0] componentsSeparatedByString:#"["] lastObject];
NSString *lastPart = [sampleParts lastObject];
But it's inefficient and didn't check whether the string is in a format like [**]**.
For this simple pattern, can just parse yourself like:
NSString *s = #"[abc]000";
NSString *firstPart = nil;
NSString *lastPart = nil;
if ([s characterAtIndex: 0] == '[') {
NSUInteger i = [s rangeOfString:#"]"].location;
if (i != NSNotFound) {
firstPart = [s substringWithRange:NSMakeRange(1, i - 1)];
lastPart = [s substringFromIndex:i + 1];
}
}
Or you could learn to use the NSScanner class.
As always, there are lots of ways to do this.
OPTION 1
If these are fixed length strings (each part is always three characters) then you can simply get the substrings directly:
NSString *sampleString = #"[abc]000";
NSString *left = [sampleString substringWithRange:NSMakeRange(1, 3)];
NSString *right = [sampleString substringWithRange:NSMakeRange(5, 3)];
NSArray *parts = #[ left, right ];
NSLog(#"%#", parts);
OPTION 1 (shortened)
NSArray *parts = #[ [sampleString substringWithRange:NSMakeRange(1, 3)],
[sampleString substringWithRange:NSMakeRange(5, 3)] ];
NSLog(#"%#", parts);
OPTION 2
If they aren't always three characters, then you can use NSScanner:
NSString *sampleString = #"[abc]000";
NSScanner *scanner = [NSScanner scannerWithString:sampleString];
// Skip the first character if we know that it will always start with the '['.
// If we can not make this assumption, then we would scan for the bracket instead.
scanner.scanLocation = 1;
NSString *left, *right;
// Save the characters until the right bracket into a string which we store in left.
[scanner scanUpToString:#"]" intoString:&left];
// Skip the right bracket
scanner.scanLocation++;
// Scan to the end (You can use any string for the scanUpToString that doesn't actually exist...
[scanner scanUpToString:#"\0" intoString:&right];
NSArray *parts = #[ left, right ];
NSLog(#"%#", parts);
RESULTS (for all options)
2013-05-10 00:25:02.031 Testing App[41906:11f03] (
abc,
000
)
NOTE
All of these assume well-formed strings, so you should include your own error checking.
try like this ,
NSString *sampleString = #"[abc]000";
NSString *pNRegex = #"\\[[a-z]{3}\\][0-9]{3}";
NSPredicate *PNTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", pNRegex];
BOOL check=[PNTest evaluateWithObject:sampleString ];
NSLog(#"success:%i",check);
if success comes as 1 then you can perform the action for separating string into array.

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! :))

Collapse sequences of white space into a single character and trim string

Consider the following example:
" Hello this is a long string! "
I want to convert that to:
"Hello this is a long string!"
OS X 10.7+ and iOS 3.2+
Use the native regexp solution provided by hfossli.
Otherwise
Either use your favorite regexp library or use the following Cocoa-native solution:
NSString *theString = #" Hello this is a long string! ";
NSCharacterSet *whitespaces = [NSCharacterSet whitespaceCharacterSet];
NSPredicate *noEmptyStrings = [NSPredicate predicateWithFormat:#"SELF != ''"];
NSArray *parts = [theString componentsSeparatedByCharactersInSet:whitespaces];
NSArray *filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
theString = [filteredArray componentsJoinedByString:#" "];
Regex and NSCharacterSet is here to help you. This solution trims leading and trailing whitespace as well as multiple whitespaces.
NSString *original = #" Hello this is a long string! ";
NSString *squashed = [original stringByReplacingOccurrencesOfString:#"[ ]+"
withString:#" "
options:NSRegularExpressionSearch
range:NSMakeRange(0, original.length)];
NSString *final = [squashed stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
Logging final gives
"Hello this is a long string!"
Possible alternative regex patterns:
Replace only space: [ ]+
Replace space and tabs: [ \\t]+
Replace space, tabs and newlines: \\s+
Performance rundown
This solution: 7.6 seconds
Splitting, filtering, joining (Georg Schölly): 13.7 seconds
Ease of extension, performance, number lines of code and the number of objects created makes this solution appropriate.
Actually, there's a very simple solution to that:
NSString *string = #" spaces in front and at the end ";
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(#"%#", trimmedString)
(Source)
With a regex, but without the need for any external framework:
NSString *theString = #" Hello this is a long string! ";
theString = [theString stringByReplacingOccurrencesOfString:#" +" withString:#" "
options:NSRegularExpressionSearch
range:NSMakeRange(0, theString.length)];
A one line solution:
NSString *whitespaceString = #" String with whitespaces ";
NSString *trimmedString = [whitespaceString
stringByReplacingOccurrencesOfString:#" " withString:#""];
This should do it...
NSString *s = #"this is a string with lots of white space";
NSArray *comps = [s componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSMutableArray *words = [NSMutableArray array];
for(NSString *comp in comps) {
if([comp length] > 1)) {
[words addObject:comp];
}
}
NSString *result = [words componentsJoinedByString:#" "];
Another option for regex is RegexKitLite, which is very easy to embed in an iPhone project:
[theString stringByReplacingOccurencesOfRegex:#" +" withString:#" "];
Try This
NSString *theString = #" Hello this is a long string! ";
while ([theString rangeOfString:#" "].location != NSNotFound) {
theString = [theString stringByReplacingOccurrencesOfString:#" " withString:#" "];
}
Here's a snippet from an NSString extension, where "self" is the NSString instance. It can be used to collapse contiguous whitespace into a single space by passing in [NSCharacterSet whitespaceAndNewlineCharacterSet] and ' ' to the two arguments.
- (NSString *) stringCollapsingCharacterSet: (NSCharacterSet *) characterSet toCharacter: (unichar) ch {
int fullLength = [self length];
int length = 0;
unichar *newString = malloc(sizeof(unichar) * (fullLength + 1));
BOOL isInCharset = NO;
for (int i = 0; i < fullLength; i++) {
unichar thisChar = [self characterAtIndex: i];
if ([characterSet characterIsMember: thisChar]) {
isInCharset = YES;
}
else {
if (isInCharset) {
newString[length++] = ch;
}
newString[length++] = thisChar;
isInCharset = NO;
}
}
newString[length] = '\0';
NSString *result = [NSString stringWithCharacters: newString length: length];
free(newString);
return result;
}
Alternative solution: get yourself a copy of OgreKit (the Cocoa regular expressions library).
OgreKit (Japanese webpage --
code is in English)
OgreKit (Google
autotranslation):
The whole function is then:
NSString *theStringTrimmed =
[theString stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
OGRegularExpression *regex =
[OGRegularExpression regularExpressionWithString:#"\s+"];
return [regex replaceAllMatchesInString:theStringTrimmed withString:#" "]);
Short and sweet.
If you're after the fastest solution, a carefully constructed series of instructions using NSScanner would probably work best but that'd only be necessary if you plan to process huge (many megabytes) blocks of text.
according from #Mathieu Godart is best answer, but some line is missing , all answers just reduce space between words , but when if have tabs or have tab in place space , like this:
" this is text \t , and\tTab between , so on "
in three line code we will :
the string we want reduce white spaces
NSString * str_aLine = #" this is text \t , and\tTab between , so on ";
// replace tabs to space
str_aLine = [str_aLine stringByReplacingOccurrencesOfString:#"\t" withString:#" "];
// reduce spaces to one space
str_aLine = [str_aLine stringByReplacingOccurrencesOfString:#" +" withString:#" "
options:NSRegularExpressionSearch
range:NSMakeRange(0, str_aLine.length)];
// trim begin and end from white spaces
str_aLine = [str_aLine stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
the result is
"this is text , and Tab between , so on"
without replacing tab the resul will be:
"this is text , and Tab between , so on"
You can also use a simple while argument. There is no RegEx magic in there, so maybe it is easier to understand and alter in the future:
while([yourNSStringObject replaceOccurrencesOfString:#" "
withString:#" "
options:0
range:NSMakeRange(0, [yourNSStringObject length])] > 0);
Following two regular expressions would work depending on the requirements
#" +" for matching white spaces and tabs
#"\\s{2,}" for matching white spaces, tabs and line breaks
Then apply nsstring's instance method stringByReplacingOccurrencesOfString:withString:options:range: to replace them with a single white space.
e.g.
[string stringByReplacingOccurrencesOfString:regex withString:#" " options:NSRegularExpressionSearch range:NSMakeRange(0, [string length])];
Note: I did not use 'RegexKitLite' library for the above functionality for iOS 5.x and above.