开发者

Remove double space in a string

I'm having a few strings, all of them having excess white spaces in the end. Having just 1 space there is not a problem, but outputting these strings in their current state into a (editable) textfield, places the 开发者_如何学Pythoncursor ~10 white spaces too far.

How can I remove double spaces in a string using Objective-C?


There are a few solutions. If you're talking about trimming whitespaces from the end of a string, you could use the NSString stringByTrimmingCharactersInSet: method as follows:

NSString *dirtyString = @"String with whitespaces at the end           ";
NSString *cleanString = [dirtyString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

Incidentally, I've choosen to use the whitespaceAndNewlineCharacterSet NSCharacterSet - the pure answer to your question would be to instead use the whitespaceCharacterSet, but I suspect that you probably also want to remove any trailing linebreaks, etc.

However, if there are double spaces within the string which you want to remove then, the NSString stringByReplacingOccurrencesOfString:withString: method should do the trick.


Try this:

NSString * trimmedString = [@"string with spaces at the end    " stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];


can your try

NSString *trimmedString = [dirtyString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

good luck

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜