See 1.2 Write code to reverse a C-Style String. (C-String means that “abcd” is represented as five characters, including the null character.)


I am not familiar with "C-Style String". Where is the null char? in the end? or in the beginning?

I assume it is in the end.


It seems convert to the string back to a char array without null char.

Reverse it. When re-build the result string, put a null char in the end.

String reverseCStyleString(String s)
{
  if (s == null)
    return s;
    
  char[] chars = CStyleString.toCharArray(s);
  
  int length = chars.length;
  for (int i = 0 ; i < length / 2 ; i ++)
  {
    // swap chars[i] and chars[length - i - 1];
    char tempChar = chars[i];
    chars[i] = chars[length - i - 1];
    chars[length - i - 1] = tempChar;
  }
  
  return CStyleString.toString(chars);
}


A trikky question: How to swap to int without extra space

int a;
int b;
int a = a + b;
int b = a - b;
int a = a - b;