TrapLevel
TrapLevel

Reputation: 135

How to manipulate character string being pointed to

I'm sure this is an easy question for most but I'm having trouble trying to figure out why I can't manipulate this sting and better yet how I should go about doing it. So for example we have:

char *str1="Hello World";

All I want to do is manipulate the string that is being pointed to by 'str1'. For example, as shown below, I could output the string and see the original. Then I could add a null character in there and shorten it.

cout << str1 << '\n';
str1[5] = '\0';
cout << str1;

I've also tried:

cout << str1 << '\n';
*(str1+4) = '\0';
cout << str1;

Either way I'm hoping to see something like this:

Hello World
Hello

The error I'm getting in both cases is when I try to alter the string. I know it would be easier to just declare str1 as an array (char str1[] = ....) but I'm given the constraint of having to use the dreaded char *

Upvotes: 0

Views: 98

Answers (3)

TrapLevel
TrapLevel

Reputation: 135

So after all of the help I've received from you all I went with first determining the length of the strings, initializing an array of the same size+1, and then iterating through the original to save it into an array. Then I was able to manipulate it as i pleased.

int someFunc(char *inpStr){
     int counter = 0;

     //Find the length of the input string
     while(inpStr[counter]!='\0'){counter++;}

     //Input initialize an array of same size
     char strArray[counter+1];

     //Copy whats in the char *   to the array and make sure it ends with null
     for(int i=0;i<=counter;i++){strArray[i]=*(inpStr+i);}
     strArray[counter]='\0';

     .....
return 0;
}

Thanks for all the help!

Upvotes: 0

SPB
SPB

Reputation: 4218

Why you cannot change the str1 has been explained aptly by Joseph. But still if you want to modify it you can use something like this:

char *str = "hello";
char *ptr = new char[strlen(str)+1];
strcpy(ptr,str);
ptr[2] = 'd';
str = ptr;

I hope this solves your problem.

Upvotes: -1

Joseph Mansfield
Joseph Mansfield

Reputation: 110658

String literals are stored in read-only memory. You cannot modify them. In fact, in modern C++, attempting to initialise str1 the way you did will give an error. It should be a const char*:

const char* str1 = "Hello World";

This makes it clear that you shouldn't be modifying the chars.

If you want a copy of the string that you can manipulate, you should make str1 an array:

char str1[] = "Hello World";

When you initialise an array with a string literal, the characters are copied into the array.

Upvotes: 4

Related Questions