Pregunta

Sorry for the rather simple question but I'm pretty new to objective-c and can't seem to find a solution to my problem that actually works with what i'm trying to do. Essentially, I have a NSString containing the a random word. For example:

NSString *word = @"Characters";

I then want to take this and split it into an array consisting of the characters so that I can index each of them:

[0] C
[1] H
[2] A

etc

It's not really important if after they're split if they're put into a NSString or an Array, as long as I can separate the string into each off the individual characters then index them.

Also for clarification, the word isn't hard coded it's randomly generated every time my program runs and pulled from a word list.

Any help is appreciated!

¿Fue útil?

Solución

There's no reason to do this. Internally, the string already is an array of characters, and you can access the individual characters by index...

[word characterAtIndex:2] // returns 'a'

Otros consejos

Update Swift 4+

Default you have a string

let string = "Characters"

so, all you need to do is...

for i:Int in 0..< string.count {
     let char = NSString(format: "%c", (string as NSString).character(at: i))
     print(char) //Optionally you can convert using 'char as String'
}

Note:- this is the update for this answer

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top