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[1] = myChar[4], but that doesn't work. Please help!

Answers


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[1];
myChar[1] = myChar[4];
myChar[4] = c1;

You assigned whatever is in myChar[4] into myChar[1]. (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[1];
myChar[1] = myChar[4];
myChar[4] = temp;

This is a very common 'algorithm' to swap two things.


Need Your Help

Spring 3.0 and EJB3 integration

spring ejb-3.0

I am trying to integrate EJB3 and Spring. I am using Jboss 5. The following is my ejb bean class

JS applications i18n and AMD (require.js)

javascript web-applications internationalization requirejs amd

Context: single page web applications written in JavaScript and AMD modules (like require.js)

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.