【问题标题】:How to add a character at the beginning of an existing string in objective-c?如何在objective-c中现有字符串的开头添加一个字符?
【发布时间】:2012-06-12 22:45:25
【问题描述】:

如何在现有字符串的开头添加单个字符,例如“$”或“+”?

我尝试使用 appendingString 方法,但在字符串末尾添加了 $+

我知道我总是可以将$+ 保存在一个新字符串中,然后附加另一个字符串,但我只是想知道是否有更好的方法。

谢谢。

【问题讨论】:

  • 你试过[@"$" stringByAppendingString: str ]

标签: iphone objective-c ios xcode ios5


【解决方案1】:

这其实很简单:

[@"+" stringByAppendingString:existingString];

这绝对适合你 :) + 将在开头。

【讨论】:

  • 问题中提到了这个解决方案。
  • @JoshCaswell 该函数是,但他说当他使用它时,它总是在函数的末尾添加+。这意味着他是在反向操作——就像这样:[existingString stringByAppendingString:@"+"];我修好了。
  • 来自问题:«我知道我总是可以将 $ 或 + 保存在一个新字符串中,然后附加另一个字符串»
【解决方案2】:

字符串是不可变的。当您使用 stringByAppendingString: 时,您正在创建一个新字符串。为了预先添加,您必须制作现有字符串的可变版本,然后使用 insertString:atIndex:,如下所示:

[[NSMutableString stringWithString:myString] insertString:@"$" atIndex:0];

为什么没有stringByPrependingString:,我不知道。

最好的解决方案是你已经提到的那个:

[@"$" stringByAppendingString:myString];

【讨论】:

    【解决方案3】:

    只要字符串是可变的,即它是一个你可以使用的 NSMutableString。

    [str insertString:@"$" atIndex:0];
    

    在此处阅读文档,https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsmutablestring_Class/Reference/Reference.html

    【讨论】:

      猜你喜欢
      • 2020-12-18
      • 2019-01-10
      • 2019-09-19
      • 1970-01-01
      • 1970-01-01
      • 2011-04-22
      • 2015-08-26
      • 2022-12-09
      • 2019-03-16
      相关资源
      最近更新 更多