Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a NSString onto another NSString

I am relatively new in Objective C but not with programming. I was wondering how you can append one NSString onto another. I am making an app in which a user has to finish a basic sentence, and I was wondering how to get the string the user entered and append it onto the current one that is on the screen?

like image 355
objective_c_pro Avatar asked Jul 03 '12 09:07

objective_c_pro


People also ask

How do I append to NSString?

Working with NSString. Instances of the class NSString are immutable – their contents cannot be changed. Once a string has been initialized using NSString, the only way to append text to the string is to create a new NSString object. While doing so, you can append string constants, NSString objects, and other values.

How to concatenate NSString in Objective C?

You use it with @"%@%@" to concatenate two strings, @"%@%@%@" to concatenate three strings, but you can put any extra characters inside, print numbers, reorder parameters if you like and so on.

What is NSString in Objective C?

(NSString *) is simply the type of the argument - a string object, which is the NSString class in Cocoa. In Objective-C you're always dealing with object references (pointers), so the "*" indicates that the argument is a reference to an NSString object.

What does NSString mean?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior. iOS 2.0+ iPadOS 2.0+ macOS 10.0+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+


2 Answers

I think you are looking for stringByAppendingString function of NSString. See the example below.

NSString *errorTag = @"Error: "; NSString *errorString = @"premature end of file."; NSString *errorMessage = [errorTag stringByAppendingString:errorString]; 

produces the string “Error: premature end of file.”.

like image 199
Ankit Avatar answered Sep 23 '22 21:09

Ankit


This could also be achieved by using a NSMutableString:

NSMutableString *string = [NSMutableString stringWithString:@"String 1"]; [string appendString:@"String 2"]; 
like image 44
Fogh Avatar answered Sep 20 '22 21:09

Fogh