开发者

Advice on editing NSStrings

For an app that I am currently making I need to break up a string into characters and then convert 开发者_开发问答each of those characters into a number. One way I thought of doing this was by using the following code;

//Get string length
int stringLength = [myString length];

//Create new variable for "While" loop
int count = stringLength;

//Start "While" loop

while (count != 0) {

    //What I want her is for the NSString to be ("letter%i",count) but I don't know how to do this 
    letter1 = [myString substringWithRange:NSMakeRange(0,stringLenght-count)];

    //each letter = 1 so it will move down one letter at a time  
    count--

}

and then I would have something like;

if (string1 == @"a") {

    number1 = 5;

}



if (string2 == @"a") {

        number2 = 5;

    }

..........

Would I be able to read the new strings that I create from outside the while loop? Any suggestions would be very helpful. Also any way to do this another way would also be helpful too.

Thanks in advance,

Jonathan


I'm not entirely clear on your intentions, but I'll try and guess. What you want to do is iterate over the string, character-by-character, and analyse each character and store your conversion into an array.

// Get length of string
NSUInteger len = [myString length];

// allocate number buffer
NSUInteger *numbers = calloc(len, sizeof(NSUInteger));

// loop through the string's characters and assign to the number array.
for (NSUInteger i = 0; i < len; i++)
{
    unichar thisChar = [myString characterAtIndex:i];

    if (thisChar == 'A')
        numbers[i] = 5;
    else if (thisChar == 'C')
        numbers[i] = 10;
}

// do what you want with the numbers array, and then free it.
free(numbers)

Also, consider using a look-up table to convert a character to a number (if there are a large number of character-to-number conversions).

And just one last thing, you can't compare strings using ==, because that will test for pointer equality, not for string equality. When you compare strings, you should use:

if ([someString isEqualToString:anotherString])
    // ... and so on ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜