8

I would like to append NSString A in front of NSString B. Is there a built in method to append to the beginning of a NSString instead of the end of the NSString?

I know that I can use stringWithFormat, but then what is the difference between using stringWithFormat and stringByAppendingString to add text to the end of a NSString?

5 Answers 5

39

If you can append to the end of a string, you can prepend to the beginning of the string.

Append

NSString* a = @"A";
NSString* b = @"B";
NSString* result = [a stringByAppendingString:b]; // Prints "AB"

Prepend

NSString* a = @"A";
NSString* b = @"B";
NSString* result = [b stringByAppendingString:a]; // Prints "BA"
0
9

Single line solution:

myString = [@"pretext" stringByAppendingString:myString];
0
4

You can use stringWithFormat too:

NSString *A = @"ThisIsStringA";
NSString *B = @"ThisIsStringB";
B = [NSString stringWithFormat:@"%@%@",A,B];

stringByAppendingString is an instance method of NSString, stringWithFormat is a class method of the class NSString.

4
  • Does instance vs class have any effect on the NSString "B"? What would be the advantage of using one over the other?
    – ansonl
    Feb 2, 2013 at 22:57
  • You have to study object oriented programming, this is a fundamental principie Feb 3, 2013 at 16:08
  • I understand that instance and class methods are different, but how does this affect usability pf NSString "B" once your have used either?
    – ansonl
    Feb 3, 2013 at 16:42
  • I'm not so good to explain it in correct English language bat to explain it I need more than a book Feb 3, 2013 at 16:45
2

It's probably worth pointing out that there is no such thing as "appending one string onto another". NSString is immutable.

In every case, you are "creating a new string that consists of one string following another".

It doesn't matter that you put the newly created string back into the same variable.

You are never "adding text to the end of a string".

-1

Here I’ve solution in Swift:

extension String {

    // Add prefix only, if there is not such prefix into a string
    mutating func addPrefixIfNeeded(_ prefixString: String?) {
        guard let stringValue = prefixString, !self.hasPrefix(stringValue) else {
            return
        }
        self = stringValue + self
    }


    // Add force full prefix, whether there is already such prefix into a string
    mutating func addPrefix(_ prefixString: String?) {
        guard let stringValue = prefixString else {
            return
        }
        self = stringValue + self
    }
} 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.