Objective-C中两个简单的字符串操作(移位操作和迭代)
我想在 obj-c 中操作 NSString 这就是我想要做的:
通过 for-each / for 循环迭代一个字符串并左移 (<<) NSString 的每个字符 但我不知道应该如何迭代 NSString 的字符以及如何在 obj-c 中使用移位运算符。
我对 Objective-c 相当陌生。
问候
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
代码:
输出:
Code:
Output:
NSString
是不可变的;mutableCopyWithZone:
将给你一个(隐式保留)NSMutableString
。但是,NSMutableString
没有设置单个字符的方法。使用多种方法之一获取字符数组会更容易(例如getCharacters:range:
用于宽字符,或cStringUsingEncoding:
,getCString:maxLength:encoding:
或UTF8String
对于 c 风格的字符串),然后对其进行操作(注意某些方法返回 const 字符串),然后使用(例如)initWithCString:encoding:
。请记住,这取决于您想要实现的目标 ,由于编码问题和多字节字符,移位字节可能不会给您期望的结果。您可以使用
length
,这是字符串中的字符数(也是单字符的大小)用于保存 UTF-16 数据的缓冲区,不包括空终止符),或lengthOfBytesUsingEncoding:
,它将告诉您保存字符串内容(不包括空终止符)的缓冲区所需的大小(字节数) 。maximumLengthOfBytesUsingEncoding:
也可用于缓冲区大小,尽管它可能大于实际所需的大小。对于可变长度编码,最大大小是最大可能的字符大小(例如,UTF-8 编码的 unichar 为 3)乘以字符数。循环和移位在其他方面与 C 中相同:将索引变量初始化为下限 (0) 并循环,直到索引变量超过上限。
如果数据不是字符串数据而是字节,
NSData
/NSMutableData
< /a> 会更合适。NSString
s are immutable;mutableCopyWithZone:
will get you an (implicitly retained)NSMutableString
. However,NSMutableString
doesn't have a way of setting individual characters. It would be easier to get an array of characters using one of the many methods (e.g.getCharacters:range:
for wide characters, orcStringUsingEncoding:
,getCString:maxLength:encoding:
orUTF8String
for c-style strings), then operate on that (note some methods return const strings), then construct a new string using (e.g.)initWithCString:encoding:
. Keep in mind that, depending on what you're trying to accomplish, shifting bytes may not give you the result you expect, due to encoding issues and multibyte characters.You can get the length of a string using
length
, which is the number of characters in the string (also the size, in unichars, of a buffer to hold UTF-16 data, not including a null-terminator), orlengthOfBytesUsingEncoding:
, which will tell you the size (number of bytes) needed for a buffer to hold the contents of the string (not including a null-terminator).maximumLengthOfBytesUsingEncoding:
can also be used for a buffer size, though it may be larger than the actual necessary size. For variable-length encodings, the maximum size is the largest possible character size (e.g. 3 for UTF-8 encoded unichars) times the number of characters.Looping and shifting is otherwise the same as in C: initialize the index variable to the lower bound (0) and loop until the index variable exceeds the upper bound.
If the data isn't string data but bytes,
NSData
/NSMutableData
would be more appropriate.