Reputation: 2930
I have a NSString that is dynamic and changes constantly. I need to take that NSString and replace occurrences of every character in it with @"" except the string @"\n"
So if I have
NSString *string = @"This is my string at 10:00PM\n I hate this string\n";
so If I remove everything except \n by replacing everything with @"" and replace the \n occurrences with 1, my new string in the end will be 11 since there are two occurrences. The string could also have any character that exists, so it needs to remove everything except \n.
How could I do this?
Upvotes: 0
Views: 210
Reputation: 32104
If you want a more convenient, albeit slightly more memory-intensive solution:
NSUInteger numNewlines = [[string componentsSeparatedByString:@"\n"] count] - 1;
NSMutableString *ones = [[NSMutableString alloc] initWithCapacity:numNewlines];
for (int i = 0; i < numNewLines; i++) {
[ones appendString:@"1"];
}
Upvotes: 1
Reputation: 10864
I think it's easier to do something like
NSString *newString = @"";
for(int i=0;i<[string length]; i++)
if([string characterAtIndex:i]=='\n')
newString = [newString stringByAppendingString:@"1"];
string = newString;
Upvotes: 0