2011-01-29 3 views
0

私が現在作っているアプリでは、文字列を文字列に分割し、それぞれの文字を数字に変換する必要があります。私がこれを行うと考えた1つの方法は、次のコードを使用することでした。NSStringの編集に関するアドバイス

//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-- 

} 

などです。

if (string1 == @"a") { 

    number1 = 5; 

} 



if (string2 == @"a") { 

     number2 = 5; 

    } 

..........

私は、whileループの外から作成した新しい文字列を読み取ることができますか?どんな提案も非常に役に立ちます。また、これを別の方法で行う方法は、あまりにも役に立ちます。事前に

おかげで、

ジョナサン

+0

数字を別々の変数に入れて、文字に変換して別の値に戻してから、すべてを一緒に長い文字列に追加できるようにします文字列。 –

答えて

3

は、私はあなたの意図に完全に明確ではないんだけど、私は試してみて思います。あなたがしたいことは文字列を文字単位で繰り返し、各文字を分析して配列に変換を保存することです。

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

また、番号(文字ツー数変換の数が多い場合)に文字を変換するためのルックアップテーブルを使用することを検討してください。

最後に、==を使用して文字列を比較することはできません。これは、文字列の等価性ではなく、ポインタの等価性をテストするためです。文字列を比較するときは、次のものを使用する必要があります。

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

ありがとう! 1つの簡単な質問。 number == 3の場合、その平均数[i]は "numbers3"ですか? –

+0

私はそれを働いたことを心配しないでください! number == 3の場合、平均値[i]は "numbers3"になります。再度、感謝します! –

関連する問題