Reputation: 17591
I have a particular problem:
in a NSSTring I have this value " abcdef ghil" I want to check if first character is a space and delete it (with stringbyreplacing...?) and in other space (from "f" to "g") I want insert a "-"
can you help me?
if it may be helpful; I take this string from a textfield...
Upvotes: 2
Views: 1014
Reputation: 8345
The following will do what you want, with the caveat that it will trim trailing whitespace as well as leading whitespace and not just a single leading or trailing whitespace character.
NSString *original = @" abcdef ghil";
NSString *trimmed = [original stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSString *final = [trimmed stringByReplacingOccurrencesOfString:@" "
withString:@"-"];
If you only want to remove leading whitespace then you should probably check out this previous question: Cocoa - Trim all leading whitespace from NSString
Update: If you really only want to remove a single space at the beginning of the string then the following should work for you:
NSString *original = @" abcdef ghil";
NSString *trimmed = [original stringByReplacingOccurrencesOfString:@" "
withString:@""
options:0
range:NSMakeRange(0, 1)];
NSString *final = [trimmed stringByReplacingOccurrencesOfString:@" "
withString:@"-"];
Upvotes: 4
Reputation: 14766
To delete the first white space you can use:
- (NSString *)stringByReplacingCharactersInRange:(NSRange)range withString:(NSString *)replacement
With a range created with NSMakeRange(0, 1), this is position 0 and length 1, you will replace the first " " with "".
With the output of this you can do simply:
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement
With this you will replace all " " with "-".
Upvotes: 0