如何截断NSString到设置的长度? [英] How can I truncate an NSString to a set length?

查看:109
本文介绍了如何截断NSString到设置的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索过,但令人惊讶地找不到答案。

I searched, but surprisingly couldn't find an answer.

我有一个长的 NSString 想缩短。我想要的最大长度是大约20个字符。我读某处,最好的解决方案是使用 substringWithRange 。这是截断字符串的最好方法吗?

I have a long NSString that I want to shorten. I want the maximum length to be around 20 characters. I read somewhere that the best solution is to use substringWithRange. Is this the best way to truncate a string?

NSRange stringRange = {0,20};
NSString *myString = @"This is a string, it's a very long string, it's a very long string indeed";
NSString *shortString = [myString substringWithRange:stringRange];

这看起来有点精致(如果字符串比最大长度短,就会崩溃)。我也不知道它是否是Unicode安全的。有更好的方法吗?

It seems a little delicate (crashes if the string is shorter than the maximum length). I'm also not sure if it's Unicode-safe. Is there a better way to do it? Does anyone have a nice category for this?

推荐答案

实际上,关于Unicode安全的部分已经死了,许多字符

Actually the part about being "Unicode safe" was dead on, as many characters combine in unicode which the suggested answers don't consider.

例如,如果要输入é。一种方法是输入e(0x65)+组合重音(0x301)。现在,如果你输入café这样和截断4个字符,你会得到咖啡馆。这可能会在某些地方造成问题。

For example, if you want to type é. One way of doing it is by typing "e"(0x65)+combining accent" ́"(0x301). Now, if you type "café" like this and truncate 4 chars, you'll get "cafe". This might cause problems in some places.

如果你不在乎,其他答案也很好。否则,请执行以下操作:

If you don't care about this, other answers work fine. Otherwise, do this:

// define the range you're interested in
NSRange stringRange = {0, MIN([myString length], 20)};

// adjust the range to include dependent chars
stringRange = [myString rangeOfComposedCharacterSequencesForRange:stringRange];

// Now you can create the short string
NSString *shortString = [myString substringWithRange:stringRange];

请注意,以这种方式,您的范围可能会比初始范围长度长。在上面的咖啡馆示例中,你的范围将扩展到5的长度,即使你仍然有4字形。如果您绝对需要的长度小于您指定的长度,那么您需要检查这一点。

Note that in this way your range might be longer than your initial range length. In the café example above, your range will expand to a length of 5, even though you still have 4 "glyphs". If you absolutely need to have a length less than what you indicated, you need to check for this.

这篇关于如何截断NSString到设置的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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