如何在不分配内存的情况下反转字符串

发布于 2025-01-06 10:54:01 字数 38 浏览 4 评论 0原文

有人问我如何在不分配内存的情况下反转字符串的问题。有接受者吗?

I was asked this question on how to reverse a string without allocating memory. Any takers?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

美胚控场 2025-01-13 10:54:02

无论是否分配内存,都无法反转 NSString,因为 NSString 是不可变的。

在不分配内存的情况下,您无法就地反转 NSMutableString,因为 NSMutableString 提供的替换其内容的唯一方法需要在 NSString< 中指定新字符。 /code>,您必须分配它。

CFMutableString 也有同样的“问题”。

You cannot reverse an NSString, with or without allocating memory, because an NSString is immutable.

You cannot reverse an NSMutableString in place without allocating memory, because the only methods that NSMutableString provides to replace its contents require the new characters to be specified in an NSString, which you would have to allocate.

CFMutableString has the same “problem”.

缺⑴份安定 2025-01-13 10:54:02
void reverseStringBetter(char* str)
{
    int i, j;
    i=j=0;

    j=strlen(str)1;
    for (i=0; i<j; i++, j-)
    {
        str[i] ^= str[j] ;
        str[j] ^= str[i] ;
        str[i] ^= str[j] ;
    }
}
void reverseStringBetter(char* str)
{
    int i, j;
    i=j=0;

    j=strlen(str)1;
    for (i=0; i<j; i++, j-)
    {
        str[i] ^= str[j] ;
        str[j] ^= str[i] ;
        str[i] ^= str[j] ;
    }
}
一身软味 2025-01-13 10:54:02

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文