Reputation: 39
I have to swap an String a="abcd" to "cdab" str="1234" to "3412". I am trying but it split each character
for (int i=2; i < [hex length]; i++) {
NSString *ichar = [NSString stringWithFormat:@"%c", [hex characterAtIndex:i]];
[characters addObject:ichar];
}
Can anyone help me out? How to split in two parts and then merge it? I am getting 4 character string from user so dont know what is coming but have to swap it.
Upvotes: 1
Views: 299
Reputation: 10175
There are plenty of solutions for this one, but I think the issue is that you don't understand the problem. As a general rule, first split the problem in parts that you understand, then try to find an implementation for each small part and I'm pretty sure that in that way you can figure it out fast and you can even find optimisations for the whole problem.
My way of thinking:
Implementation:
1 & 2. NSString *final = [str substringWithRange:NSMakeRange(str.length / 2, str.length / 2)];
[final stringByAppendingString:[str substringWithRange:NSMakeRange(0, str.length / 2)]]
; All code in one snipped:
NSString *str = @"ABCD";
NSString *final = [str substringWithRange:NSMakeRange(str.length / 2, str.length / 2)];
final = [final stringByAppendingString:[str substringWithRange:NSMakeRange(0, str.length / 2)]];
NSLog(@"%@",final);
Upvotes: 2