删除NSString中的多个空格 [英] Removing multiple spaces in NSString

查看:151
本文介绍了删除NSString中的多个空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 NSString ,这有多个空格,我想修剪那些空格并为@如何.....是...... .....你进@你好吗。(点只是空格)

I have a NSString, this has multiple spaces, I want to trim those spaces and make a single space for e.g.@"how.....are.......you" into @"how are you".(dots are simply spaces)

我试过了

NSString *trimmedString = [user_ids stringByTrimmingCharactersInSet:
                           [NSCharacterSet whitespaceCharacterSet]];

它似乎不起作用。任何想法。

It not seems to work. Any idea.

推荐答案

您可以使用正则表达式来完成此任务:

You could use a regular expression to accomplish this:

NSError *error = nil;

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"  +" options:NSRegularExpressionCaseInsensitive error:&error];

该模式是一个空格,后跟一个或多个空格。将其替换为字符串中的单个空格:

The pattern is a space followed by one or more occurrences of space. Replace this with a single space in your string:

NSString *trimmedString = [regex stringByReplacingMatchesInString:user_ids options:0 range:NSMakeRange(0, [user_ids length]) withTemplate:@" "];

这篇关于删除NSString中的多个空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆