2010-04-23 52 views
4

我使用thsi函數從字符串中檢索不同的字符,並向它們添加5以顯示例如對應的字符。 'a'顯示'f','h'顯示'm'.. 但問題是我無法將這些字符添加到字符串中,我可以使用它來顯示像'fm'...可以任何人幫助?繼承人代碼 strResult(mutablestring)僅爲空。將不同的字符逐個添加到NSString中?

[email protected]"John"; 

int a=[str length]; 

for(i=0;i<a;i++) 
{ 
    char ch=[str characterAtIndex:i]; 
    ch=ch+5; 
    temp=[NSString stringWithFormat:@"%c",ch]; 
    [strResult appendString:temp]; 
    NSLog(@"%c",ch); 
} 
+1

strResult是如何定義的,你有什麼地方初始化它? – Vladimir 2010-04-23 09:10:40

回答

17

首先,你需要確保你分配的字符串strResult,就像這樣:

NSMutableString *strResult = [NSMutableString string]; 

二;您可以並且確實應該使用-appendFormat:將字符添加到字符串;臨時額外的字符串是相當無用的。

你想要什麼,然後:

NSString *str = @"abcdef"; 
NSMutableString *strResult = [NSMutableString string]; 

for (NSUInteger i = 0; i < [str length]; i++) { 
    char ch = [str characterAtIndex:i] + 5; 
    NSLog(@"%c", ch); 
    [strResult appendFormat:@"%c", ch]; 
} 
NSLog(@"%@", strResult); 

這將產生:

f 
g 
h 
i 
j 
k 
fghijk