对于我正在制作的应用,我需要将字符串分解为字符,然后将每个字符转换为数字。我想到这样做的一种方法是使用以下代码;
//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 ...