Add to top of NSString method

I would like to add NSString Abefore NSString B. Is there a built-in method to append to the beginning of an NSString instead of the end of an NSString?

I know I can use it stringWithFormat, but then what is the difference between using stringWithFormatand stringByAppendingStringadding text to the end of an NSString?

+5
source share
5 answers

If you can add the end of the line, you can go to the beginning of the line.

Append

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

Prepare

NSString* a = @"A";
NSString* b = @"B";
NSString* result = [b stringByAppendingString:a]; // Prints "BA"
+34
source

Single Line Solution:

myString = [@"pretext" stringByAppendingString:myString];
+9
source

stringWithFormat:

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

stringByAppendingString - NSString, stringWithFormat - NSString.

+4

, , , " ". NSString .

, , .

It doesn’t matter that you return the newly created string to the same variable.

You never add text to the end of a line.

+2
source

Here's an Ive 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
    }
} 
0
source

All Articles