Converting NSArray to NSString [duplicate] - objective-c

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 :)

Related

Split a string into a character array - Objective-C [duplicate]

This question already has answers here:
Is there a simple way to split a NSString into an array of characters?
(4 answers)
Closed 6 years ago.
I am building a PygLatin App and would like to know how to split a string into a character array.
For example:
If the user inputs "hello world" I would want to be able to split hello into an array variable that stores it as [#"h",#"e",#"l",#"l",#"o"] so that I can compare it with the vowels array later.
Those functions must help you to do it.
NSString *str=#"hello world"; // your string
NSArray *items = [str componentsSeparatedByString:#" "]; //split string with separator
NSString *str1=[items objectAtIndex:0]; // get the first string
SString *str2=[items objectAtIndex:1];
for (int i=0; i < [str1 length]; i++) {
unichar mycharacter = [str1 characterAtIndex:0];
NSString * mycharasstring= [NSString stringWithFormat:#"%c", mycharacter];
[self.myarray addobject: [myString characterAtIndex:i]]; // add characters to your array
}

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

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.

How to split an NSString into multiple NSStrings [duplicate]

This question already has answers here:
Is there a simple way to split a NSString into an array of characters?
(4 answers)
Closed 8 years ago.
I'm trying to split an NSString into multiple NSString's. One new string for every character in the NSString. Is there a simpler way to do this than just doing it manually? A method or API that can do this automatically?
For example, turn this string:
_line1 = [NSString stringWithFormat:#"start"];
into:
_string1 = [NSString stringWithFormat:#"s"];
_string2 = [NSString stringWithFormat:#"t"];
_string3 = [NSString stringWithFormat:#"a"];
_string4 = [NSString stringWithFormat:#"r"];
_string5 = [NSString stringWithFormat:#"t"];
The documentation out there is really good. There are lots of ways you could do this.
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html
One way is to make an array of NSStrings that contain each character.
NSString * line1 = #"start";
NSMutableArray * characters = [NSMutableArray array];
for(int i = 0; i < line1.length; i++) {
NSString * character = [line1.substringWithRange:NSMakeRange(i, 1)];
[characters addObject:character];
}
// Then loop over characters array ...
First off, why are you using _line1? You should never access properties directly via their pointer. Please use self.line1 instead. I will assume you have #property NSString *line1; in your class definition. If not, you'll need to adjust the code I'm posting as necessary.
Second, no there's no way built in. But it's pretty simple to do manually:
NSMutableArray *chars = [NSMutableArray array];
NSUinteger i = 0;
for (i = 0; i < self.line1.length; i++) {
[chars addObject:[self.line1 substringWithRange:NSMakeRange(i, 1)]];
}

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.