ab jatoi ab jatoi - 17 days ago 7
iOS Question

How to swap string in Objective c without any space?

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.

Answer

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:

  1. Split the string in half.
  2. Second half is first
  3. First half is added last.

Implementation:

1 & 2. NSString *final = [str substringWithRange:NSMakeRange(str.length / 2, str.length / 2)];

  1. [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);
Comments