如何将 NSString 分成多个八位字节
我想将 NSString 拆分为每个 NSString 不超过 75 个八位字节(以 UTF8 表示)。
如果我的 NSString 完全是 ascii 那就很容易了。
但由于生成的字符串可以有 18 到 75 个字符之间的任意长度,我不知道该怎么做。
有什么方法可以做到这一点?
将字符串转换为八位字节,取出前 75 个字符,将其转换回 NSString 并希望 NSString 告诉我我已将 utf8 字符分成两部分?
I want to split a NSString into NSStrings that have no more than 75 octets (in UTF8 representation) each.
If my NSString would be completely ascii it would be a no-brainer.
But since the resulting string could have any length between 18 and 75 characters I have no real idea how to do it.
what's the way to do this?
Convert the string into octets, take the first 75, convert it back to NSString and hope that NSString tells me that I've ripped an utf8-character into two parts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
沃伦的回答告诉我,我走在正确的道路上。这就是我想出的:
the answer of warren showed me that I was on the right track. This is what I came up with:
NSString
具有- (NSData *)dataUsingEncoding:(NSStringEncoding)encoding allowedLossyConversion:(BOOL)flag
给出未终止的 C 字符串,但允许丢失字符
- (const char *)cStringUsingEncoding:(NSStringEncoding)encoding
将尝试为您提供一个 C 字符串,但如果它不能无损地执行此操作,则会返回 NULL
,这可能是检测您即将分解一对的一种方法。
NSString
has- (NSData *)dataUsingEncoding:(NSStringEncoding)encoding allowLossyConversion:(BOOL)flag
gives a unterminated C string but allows loss of chars
- (const char *)cStringUsingEncoding:(NSStringEncoding)encoding
will attempt to give you a C string but barf to NULL if it cant do it losslessly
which could be a way to detect that you are about to break up a pair.