xcode 如何在objective-c中现有字符串的开头添加一个字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11005944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add a character at the beginning of an existing string in objective-c?
提问by wackytacky99
How do I add a single character such as a '$
' or a '+
' at the beginning of an existing string?
如何在现有字符串的开头添加单个字符,例如 ' $
' 或 ' +
'?
I tried using the appendingString method but that adds the $
or +
at the end of the string.
我尝试使用 appendString 方法,但是在字符串的末尾添加了$
或+
。
I know I can always save the $
or +
in a new string and then append the other string, but I just want to know if there is a better way to do it.
我知道我总是可以将$
或保存+
在一个新字符串中,然后附加另一个字符串,但我只想知道是否有更好的方法来做到这一点。
Thank you.
谢谢你。
回答by WendiKidd
This is actually very simple:
这其实很简单:
[@"+" stringByAppendingString:existingString];
This should definitely work for you :) And the +
will be at the beginning.
这绝对适合您:) 并且+
将在开始时。
回答by jscs
Strings aren't mutable. You're creating a new string when you use stringByAppendingString:
In order to prepend, you would have to make a mutable version of your existing string and then use insertString:atIndex:
like so:
字符串是不可变的。您在使用时正在创建一个新字符串stringByAppendingString:
为了预先添加,您必须创建现有字符串的可变版本,然后insertString:atIndex:
像这样使用:
[[NSMutableString stringWithString:myString] insertString:@"$" atIndex:0];
Why there isn't a stringByPrependingString:
, I don't know.
为什么没有stringByPrependingString:
,我不知道。
The best solution is the one you've already mentioned:
最好的解决方案是您已经提到的解决方案:
[@"$" stringByAppendingString:myString];
回答by Ben Trengrove
As long as the string is mutable, i.e. it is an NSMutableString you can use.
只要字符串是可变的,即它是您可以使用的 NSMutableString。
[str insertString:@"$" atIndex:0];
Have a read of the docs here, https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsmutablestring_Class/Reference/Reference.html