Dynamically change number of variables in NSStringWithFormat - objective-c

Let's say I have string like this:
NSString *myString = [NSString stringWithFormat:#"%#%#%#%#%#",variable1,variable2,variable3,variable4,variable5];
and if variable2 is nil I don't want that in my string, like this:
NSString *myString = [NSString stringWithFormat:#"%#%#%#%#",variable1,variable3,variable4,variable5];
Question
Is there any way to do this without having a lot of if-statements?

Don't use [NSString stringWithFormat:], and instead create an NSMutableString and append strings as necessary:
NSMutableString *s = [[NSMutableString alloc] init];
if (variable1)
[s appendString:variable1];
if (variable2)
[s appendString:variable2];
if (variable3)
[s appendString:variable3];
if (variable4)
[s appendString:variable4];
if (variable5)
[s appendString:variable5];
(sorry I missed your point about "not having lots of if statements", however I don't think it can be avoided).

The easiest way is to use the compacted ternary operator to replace a null with an empty string. Using a slightly abridged version of your example:
NSString *myString = [NSString stringWithFormat:#"%#%#",variable1 ?: #"",variable2 ?: #""];

Related

why will the following code not append one string to the other?

it is the question from my friends. I have research some code from the internet but no help, i think it should working, the question is right.
NNString *s = [[NNString alloc]initWithString:#"hello"];
[s appendString:#"there"];
NSString is immutable, you'd need to use an instance of NSMutableString in order to be able to append to it.
NSMutableString *s = [[NSMutableString alloc] initWithString:#"hello"];
[s appendString:#"there"];
Alternatively you could replace the instance using stringByApendingString:.
Try this if you want to keep the string immutable:
s = [s stringByAppendingString:#" there"];

Concatenate String in String Objective-c

I want to place a string within a string. Basically in pseudo code:
"first part of string" + "(varying string)" + "third part of string"
How can I do this in objective-c? Is there a way to easily concatenate in obj-c? Thanks!
Yes, do
NSString *str = [NSString stringWithFormat: #"first part %# second part", varyingString];
For concatenation you can use stringByAppendingString
NSString *str = #"hello ";
str = [str stringByAppendingString:#"world"]; //str is now "hello world"
For multiple strings
NSString *varyingString1 = #"hello";
NSString *varyingString2 = #"world";
NSString *str = [NSString stringWithFormat: #"%# %#", varyingString1, varyingString2];
//str is now "hello world"
Variations on a theme:
NSString *varying = #"whatever it is";
NSString *final = [NSString stringWithFormat:#"first part %# third part", varying];
NSString *varying = #"whatever it is";
NSString *final = [[#"first part" stringByAppendingString:varying] stringByAppendingString:#"second part"];
NSMutableString *final = [NSMutableString stringWithString:#"first part"];
[final appendFormat:#"%# third part", varying];
NSMutableString *final = [NSMutableString stringWithString:#"first part"];
[final appendString:varying];
[final appendString:#"third part"];
NSString * varyingString = ...;
NSString * cat = [NSString stringWithFormat:#"%s%#%#",
"first part of string",
varyingString,
#"third part of string"];
or simply -[NSString stringByAppendingString:]
You would normally use -stringWithFormat here.
NSString *myString = [NSString stringWithFormat:#"%#%#%#", #"some text", stringVariable, #"some more text"];
Just do
NSString* newString=[NSString stringWithFormat:#"first part of string (%#) third part of string", #"foo"];
This gives you
#"first part of string (foo) third part of string"
Iam amazed that none of the top answers pointed out that under recent Objective-C versions (after they added literals), you can concatenate just like this:
#"first" #"second"
And it will result in:
#"firstsecond"
You can not use it with NSString objects, only with literals, but it can be useful in some cases.
simple one:
[[#"first" stringByAppendingString:#"second"] stringByAppendingString:#"third"];
if you have many STRINGS to Concatenate, you should use NSMutableString for better performance

Simple int to NSString conversion as in Java?

Is there any simple way how to initialize String in Objective-C with int such as in Java:
String myStr = 42 + "";
or I have to do
[NSString stringWithFormat:#"%d", 42];
everytime?
You could also use the NSNumber class for that:
NSNumber *number = [[NSNumber alloc] initWithInteger: val];
NSString *string = [number stringValue];
Perhaps not shorter, but it could be eventually faster.
Also you could create as said a helper method, than you wouldn't have to use more code than with the stringWithFormat: method.
Yes you have to do
[NSString stringWithFormat:#"%d", 42];
for Integer to string conversion.
Using a constant, like 42 in your example, you can write
NSString *myString = #"42";
Using a variable or expression, you can write
[NSString stringWithFormat:#"%d", myValue];

Change value of mutable string

How to change value of mutable string ? Here is what I do
NSString *str = #"This is string";
NSMutableString *str = [NSMutableString stringWithFormat:#"%#", str];
str = #"New string" -> wrong incompatible pointer types assigning to NSMutableString from NSString
You only need to use NSMutableString if you want to change parts of the string in place (append, insert etc.), often for performance reasons.
If you want to assign new values to the string variable, you're fine with a good old NSString as your last line simple assigns a complete new string object to str:
You can use setString to replace the whole string:
NSString *str = #"This is string";
NSMutableString *mutableStr = [NSMutableString stringWithFormat:#"%#", str];
...
[mutableStr setString:#"a different non mutable string"];
As indicated in another answer, a non-mutable NSString may be enough for your purposes.
This is how you should initialize a NSMutableString:
NSMutableString *string = [[NSMutableString alloc]init];
You could use any other way specified in the docs. The way you are doing it, you are not creating any instance of the NSMutableString class. Then, if you want to add some string to it:
[string appendString:#"content"];

Merge 5 NSStrings in Objective-C

I have multiple NSStrings and i wish to merge them into one other, here is my code so far...
NSString *newURL = [_parameters objectForKey:#"url"];
NSString *emailBody = #"Hey!<br>I just snipped my long url with My Cool App for iPhone in just a few seconds!<p><b>"+newURL+#"</b></p>";
If you know the number of your existing strings, you can just concat them:
NSString* longString = [firstString stringByAppendingString:secondString];
or:
NSString* longString = [NSString stringWithFormat:#"A string: %#, a float: %1.2f", #"string", 31415.9265];
If you have an arbitrary number of strings, you could put them in an NSArray and join them with:
NSArray* chunks = ... get an array, say by splitting it;
NSString* string = [chunks componentsJoinedByString: #" :-) "];
(Taken from http://borkware.com/quickies/one?topic=NSString)
Another good resource for string handling in Cocoa is: "String Programming Guide"
You can try
NSString *emailBody = [ NSString stringWithFormat: #"Hey!<br>I just snipped my long url with Snippety Snip for iPhone in just a few seconds, why not check it out?<p><b>%#</b></p>", newURL ];
Given that you've got multiple strings I recommend using an Array:
NSArray *array = [NSArray arrayWithObjects:#"URL", #"person", "body"];
NSString *combined = [array componentsJoinedByString:#""];
Formatting string has better readability and less error-prone:
NSString *newURL = [_parameters objectForKey:#"url"];
NSString *emailBody = [NSString stringWithFormat:#"Hey!<br>I just snipped my long url with Snippety Snip for iPhone in just a few seconds, why not check it out?<p><b>%#</b></p>", newUrl, newUrl];
You can concatenate strings in Cocoa using:
[NSString stringByAppendingString:]
Or you could use the [NSString stringWithFormat] method which will allow you to specify a C-style format string with a variable argument list to populate the escape sequences.