How to replace a character in NSString without inserting a space?
Let's assume I have the string
NSString* myString = @"Hello,";
How can I remove the comma without leaving a space? I have tried:
NSString* newString = [myString stringByReplacingOccurrencesOfString:@"," withStri开发者_如何转开发ng:@""];
and
NSString* newString = [myString stringByTrimmingCharactersInSet:[NSCharacterSet punctuationCharacterSet]];
But both are leaving spaces.
I just ran the following as a test
NSString * myString = @"Hello,";
NSString * newString = [myString stringByReplacingOccurrencesOfString:@"," withString:@""];
NSLog(@"%@xx",newString);
And I get 2010-04-05 18:51:18.885 TestString[6823:a0f] Helloxx
as output. There is no space left.
NSString *newString = [myString substringToIndex:5];
That will ensure that there are only 5 characters in the string, but beware that this will also throw an exception if there are not at least 5 characters in the string to begin with. How are you handling this string? Is it being displayed to the user? Is it being written to a file? The code that you posted does not reproduce the error, so perhaps you should post the code that you are having a problem with.
the other way u can use.. by stringByReplacingCharactersInRange
token = [token stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:@"*"];
"token"is your want to replace the NSString and "i" is you want to change NSString by "*"
精彩评论