NSString用单个换行符替换重复的换行符 [英] NSString replace repeated newlines with single newline

查看:144
本文介绍了NSString用单个换行符替换重复的换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 NSString ,它可以在字符串之间有多个\ n。我需要用单个\ n替换多次出现的\ n。

I have an NSString which can have multiple \n in between the string. I need to replace the multiple occurrence of \n's with a single \n.

我试过这段代码:

newString = [string stringByReplacingOccurrencesOfString:@"\n\n" withString:@"\n"];

但是,如果出现一系列\ n \ n在字符串中遇到n \ nn \ n \\ n。在这种情况下,它们将被替换为\ n \ nn \ n。

But this does not give the desired result if a series of "\n\n\n\n\n\n" is encountered in the string. In this case, they will be replaced with "\n\n\n".

我该怎么办才能使所有多个\ n用单个\ n取代?

What should I do so that all more than one "\n"s be replaced with single "\n"?

全部谢谢!

更新:添加已过滤字符串设置为文本的 UITextView 的屏幕截图。根据Attila H的回答,在编写代码后,新行似乎不止一行。

Update: Adding a screenshot for UITextView to which the filtered string is set as text. The new lines seem to be more than one after writing code as suggested by Attila H in answer.

推荐答案

您可以使用 NSRegularExpression 。这是最简单和优雅的方式:

You might use NSRegularExpression. This is the most simple and elegant way:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\n+" options:0 error:NULL];
NSString *newString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@"\n"];

这篇关于NSString用单个换行符替换重复的换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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