How can I rearrange the chars in a char*?
I have char* myChar = "HELLO". I would like to switch the places of the E and the O. I tried doing myChar = myChar, but that doesn't work. Please help!
First off, that string literal is probably being stored in read-only memory. You can fix that by declaring the string as an array of characters:
char myChar = "HELLO";
To swap the characters, you'll have to use a temporary variable:
char c1 = myChar; myChar = myChar; myChar = c1;
You assigned whatever is in myChar into myChar. (that's all you did there) You need to create a temporary variable char temp; and do the following:
Edit: As mentioned by Tim Cooper, char myChar = "HELLO"; - // This will remove it's constness. temp = myChar; myChar = myChar; myChar = temp;
This is a very common 'algorithm' to swap two things.