wackytacky99
wackytacky99

Reputation: 614

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.

Upvotes: 0

Views: 6332

Answers (3)

jscs
jscs

Reputation: 64002

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];

Upvotes: 4

WendiKidd
WendiKidd

Reputation: 4373

This is actually very simple:

[@"+" stringByAppendingString:existingString];

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

Upvotes: 10

Ben Trengrove
Ben Trengrove

Reputation: 8729

As long as the string is mutable, i.e. 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

Upvotes: 1

Related Questions