简体   繁体   中英

How to add a character at the beginning of an existing string in objective-c?

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.

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.

This is actually very simple:

[@"+" stringByAppendingString:existingString];

This should definitely work for you :) And the + will be at the beginning.

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:

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

Why there isn't a stringByPrependingString: , I don't know.

The best solution is the one you've already mentioned:

[@"$" stringByAppendingString:myString];

As long as the string is mutable, ie it is an NSMutableString you can use.

[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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM