如何在不分配内存的情况下反转字符串
有人问我如何在不分配内存的情况下反转字符串的问题。有接受者吗?
I was asked this question on how to reverse a string without allocating memory. Any takers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
无论是否分配内存,都无法反转
NSString
,因为NSString
是不可变的。在不分配内存的情况下,您无法就地反转
NSMutableString
,因为NSMutableString
提供的替换其内容的唯一方法需要在NSString< 中指定新字符。 /code>,您必须分配它。
CFMutableString
也有同样的“问题”。You cannot reverse an
NSString
, with or without allocating memory, because anNSString
is immutable.You cannot reverse an
NSMutableString
in place without allocating memory, because the only methods thatNSMutableString
provides to replace its contents require the new characters to be specified in anNSString
, which you would have to allocate.CFMutableString
has the same “problem”.NSString 是不可能的,因为它们是不可变的,唯一的方法是创建一个新字符串。
尽管这可能不是您想要的,但您可以将
NSString
转换为普通的 c 字符串,并就地编辑它。您仍在分配内存,但通过就地修改字符串,您至少可以获得所需的一半。我不确定您不想分配内存的用例是什么,或者这是否只是一个假设。
It is not possible with
NSString
since they are immutable and the only way is to create a new string.Though this might not be what you are looking for, you can convert the
NSString
to a normal c-string, and edit that in-place. You are still allocating memory, but you'll at least get half of what you want by being able to modify the string in place.I'm not sure what your use case is for not wanting to allocate memory, or if this is simply a hypothetical.