Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add different characters to a NSString one by one?

i am retrieving different characters from a string by using thsi function and adding 5 to them to display the corresponding character for eg. 'a' displays 'f' and 'h' displays 'm'.. but the problem is that i am not able to add these characters into a string which i can use to display to display like 'fm'...can anyone help?? heres the code strResult(mutablestring) is getting null only.

str=@"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);
}
like image 658
hemant Avatar asked Apr 23 '10 09:04

hemant


1 Answers

First of all, you need to make sure you allocate the string strResult, like so:

NSMutableString *strResult = [NSMutableString string];

Second; you can, and indeed should, use -appendFormat: for adding the characters to the string; the temporary extra string is pretty useless.

What you want then:

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

This should produce:

f
g
h
i
j
k
fghijk
like image 106
Williham Totland Avatar answered Sep 24 '22 18:09

Williham Totland