Append to beginning of NSString method
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".
Comments
-
ansonl almost 2 years
I would like to append NSString
A
in front of NSStringB
. 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 usingstringWithFormat
andstringByAppendingString
to add text to the end of a NSString? -
ansonl over 11 yearsDoes instance vs class have any effect on the NSString "B"? What would be the advantage of using one over the other?
-
Giuseppe Mosca over 11 yearsYou have to study object oriented programming, this is a fundamental principie
-
ansonl over 11 yearsI understand that instance and class methods are different, but how does this affect usability pf NSString "B" once your have used either?
-
Giuseppe Mosca over 11 yearsI'm not so good to explain it in correct English language bat to explain it I need more than a book