xcode 如何遍历目标 c 中的 NSString?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9957106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I iterate through an NSString in objective c?
提问by Justin Copeland
How can iterate through an NSString object in Objective c whiling maintaining an index for the character I am currently at?
在为我当前所在的角色维护索引的同时,如何遍历 Objective c 中的 NSString 对象?
I want to increment the ASCII value of every third character by 3, and then print this incremented character in a label in my user interface.
我想将每三个字符的 ASCII 值增加 3,然后在我的用户界面的标签中打印这个增加的字符。
回答by Vinnie
Wasn't clear whether you just wanted to print the incremented characters or all. If the former, here's is how you would do it:
不清楚您是只想打印递增的字符还是全部。如果是前者,您可以这样做:
NSString *myString = @"myString";
NSMutableString *newString = [NSMutableString string];
for (int i = 0; i < [myString length]; i++)
{
int ascii = [myString characterAtIndex:i];
if (i % 3 == 0)
{
ascii++;
[newString appendFormat:@"%c",ascii];
}
}
myLabel.text = newString;
回答by Richard J. Ross III
Will this do the trick?
这会奏效吗?
NSString *incrementString(NSString *input)
{
const char *inputUTF8 = [input UTF8String]; // notice we get the buffers so that we don't have to deal with the overhead of making many message calls.
char *outputUTF8 = calloc(input.length + 1, sizeof(*outputUTF8));
for (int i = 0; i < input.length; i++)
{
outputUTF8[i] = i % 3 == 0 ? inputUTF8[i] + 3 : inputUTF8[i];
}
NSString *ret = [NSString stringWithUTF8String:outputUTF8];
free(outputUTF8); // remember to free the buffer when done!
return ret;
}