Sheehan Alam
Sheehan Alam

Reputation: 60879

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:@"," withString:@""];

and

NSString* newString = [myString stringByTrimmingCharactersInSet:[NSCharacterSet punctuationCharacterSet]];

But both are leaving spaces.

Upvotes: 32

Views: 51665

Answers (3)

qn5566
qn5566

Reputation: 1

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 "*"

Upvotes: 0

dreamlax
dreamlax

Reputation: 95335

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.

Upvotes: 0

user120587
user120587

Reputation:

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.

Upvotes: 108

Related Questions