Merge 5 NSStrings in Objective-C - 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.

Related

Check if it is possible to break a string into chunks?

I have this code who chunks a string existing inside a NSString into a NSMutableArray:
NSString *string = #"one/two/tree";
NSMutableArray *parts = [[string componentsSeparatedByString:#"/"] mutableCopy];
NSLog(#"%#-%#-%#",parts[0],parts[1],parts[2]);
This command works perfectly but if the NSString is not obeying this pattern (not have the symbol '/' within the string), the app will crash.
How can I check if it is possible to break the NSString, preventing the app does not crash?
Just check parts.count if you don't have / in your string (or only one), you won't get three elements.
NSString *string = #"one/two/tree";
NSMutableArray *parts = [[string componentsSeparatedByString:#"/"] mutableCopy];
if(parts.count >= 3) {
NSLog(#"%#-%#-%#",parts[0],parts[1],parts[2]);
}
else {
NSLog(#"Not found");
}
From the docs:
If list has no separators—for example, "Karin"—the array contains the string itself, in this case { #"Karin" }.
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/componentsSeparatedByString:
You might be better off using the "opposite" function to put it back together...
NSString *string = #"one/two/three";
NSArray *parts = [string componentsSeparatedByString:#"/"];
NSString *newString = [parts componentsJoinedByString:#"-"];
// newString = #"one-two-three"
This will take the original string. Split it apart and then put it back together no matter how many parts there are.

Converting NSArray to NSString [duplicate]

This question already has answers here:
Convert NSArray to NSString in Objective-C
(9 answers)
Closed 9 years ago.
I wish to know how to convert an NSArray (for example: ) into an Objective-C string (NSString).
Also, how do I concatenate two strings together? So, in PHP it's:
$variable1 = "string one":
$variable2 = $variable1;
But I need it in Objective-C
Possible duplication: Convert NSArray to NSString in Objective-C
Firstly, that is not PHP concatenation, This is:
$variable1 = "Hello":
$variable1 .= "World";
see: https://stackoverflow.com/a/11441389/1255945
Next, Stackoverflow isnt a personal tutor. You should only post here specific problems and provide as much code and information as you can, not just stuff thats basically saying "I cant be bothered to look myself, tell me".
I must admit I have done this myself so i'm not having a go at you, just trying to be polite as share my knowledge and experience
With that in mind, to convert an NSArray to NSString
Taken from: http://ios-blog.co.uk/tutorials/objective-c-strings-a-guide-for-beginners/
NSString * resultString = [[array valueForKey:#"description"] componentsJoinedByString:#""];
If you want to split the string into an array use a method called componentsSeparatedByString to achieve this:
NSString *yourString = #"This is a test string";
NSArray *yourWords = [myString componentsSeparatedByString:#" "];
// yourWords is now: [#"This", #"is", #"a", #"test", #"string"]
if you need to split on a set of several different characters, use NSString’s componentsSeparatedByCharactersInSet:
NSString *yourString = #"Foo-bar/iOS-Blog";
NSArray *yourWords = [myString componentsSeparatedByCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:#"-/"]
];
// yourWords is now: [#"Foo", #"bar", #"iOS", #"Blog"]
Note however that the separator string can’t be blank. If you need to separate a string into its individual characters, just loop through the length of the string and convert each char into a new string:
NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[myString length]];
for (int i=0; i < [myString length]; i++) {
NSString *ichar = [NSString stringWithFormat:#"%c", [myString characterAtIndex:i]];
[characters addObject:ichar];
}
Hope this helps, and Good luck developing :)

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

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"];

Get a string with ascii code objective-c

I have a ascii code, for the letter 'a', and I want to get a string by its ascii code, is it possible with NSString?
This could also work:
NSString *foo = [NSString stringWithFormat:#"%c", 97];
Didn’t test it.
If you mean you have a byte that represents an ASCII-encoded character and you want to make a string out of it, NSString has an initializer just for that.
char characterCodeInASCII = 97;
NSString *stringWithAInIt = [[NSString alloc] initWithBytes:&characterCodeInASCII length:1 encoding:NSASCIIStringEncoding];