简体   繁体   English

如何在目标c中迭代NSString?

[英]How do I iterate through an NSString in objective c?

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,然后在我的用户界面中的标签中打印此递增的字符。

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;

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM