Append to beginning of NSString method

13,593

Solution 1

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"

Solution 2

Single line solution:

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

Solution 3

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.

Solution 4

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".

Share:
13,593
ansonl
Author by

ansonl

Develop. Run. Eat.

Updated on June 28, 2022

Comments

  • ansonl
    ansonl almost 2 years

    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?

  • ansonl
    ansonl over 11 years
    Does instance vs class have any effect on the NSString "B"? What would be the advantage of using one over the other?
  • Giuseppe Mosca
    Giuseppe Mosca over 11 years
    You have to study object oriented programming, this is a fundamental principie
  • ansonl
    ansonl over 11 years
    I understand that instance and class methods are different, but how does this affect usability pf NSString "B" once your have used either?
  • Giuseppe Mosca
    Giuseppe Mosca over 11 years
    I'm not so good to explain it in correct English language bat to explain it I need more than a book