Cocoa xcode4.3 hide characters of a string - objective-c

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

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
)

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

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 can I parse this string using NSString?

I have the following string:
callback({"Outcome":"Success", "Message":null, "Identity":"Request", "Delay":0.002, "Symbol":"AAPL", "CompanyName":"Apple Inc.", "Date":"1\/13\/2011", "Time":"4:02:36 PM", "Open":344.6, "Close":345.93, "PreviousClose":344.42, "High":346.63, "Low":343.86, "Last":345.93, "Change":1.51, "PercentChange":0.438, "Volume":785960})
I want my final string to not contain callback( and the the last ) at the end of the string. How can I modify this NSString?
NSScanner is a good fit for this sort of thing.
NSString *json = nil;
NSScanner *scanner = [NSScanner scannerWithString:fullString];
[scanner scanUpToString:#"{" intoString:NULL]; // Scan to where the JSON begins
[scanner scanUpToString:#")" intoString:&json];
NSLog(#"json = %#", json);
Make an NSMutableString out of it, called string. i.e. NSMutableString *string = [NSMutableString stringWithString:myString];.
Then do string = [string substringToIndex:[string length]-1]; and then string = [string substringFromIndex:9]; or some such.
Or, again create an NSMutableString instance with your NSString instance, and call [string replaceOccurrencesOfString:#"callback(" withString:#"" options:NSLiteralSearch range:NSMakeRange(0, [string length])]; and [string replaceOccurrencesOfString:#")" withString:#"" options:NSLiteralSearch range:NSMakeRange(0, [string length])];. This might be preferred.
Either way, then create an NSString instance with the new string, something like goodString = [NSString stringWithString:string]; if you need an NSString out of this.
You can't modify an NSString (only an NSMutableString), but you can use [string substringWithRange:NSMakeRange(9, [string length] - 10)]. To actually mutate an NSMutableString, you'd have to use two deleteCharactersInRange: calls to trim the parts you don't want.