I want to delete a Newline ‘\n’ within a string.
char *string ="hallo\n";
int i=0;
int length = sizeof(string);
while(i<length)
{
if(string[i+1] == '\n')
{
string[i+1] = '\0';
break;
}
i++;
}
printf("%s",string);
printf("world");
I know that I could just spawn a new array and it works like this
char *string ="hallo\n";
int i=0;
int length = sizeof(string);
int lengthNew = length -1;
char newStr[lengthNew];
while(i<length)
{
printf("Char ist %c:",string[i]);
newStr[i] = string[i];
if(string[i+1] == '\n')
break;
i++;
}
But why using stack if I just could substitude one character in the old array?
If the newline is always the last character of the string, you could code it like you have described.
Otherwise you’d have to create a second character buffer and copy the characters to the second buffer. The reason for this is that in C the
\0character marks the end of the string.If you have a string like this:
"this \n is \n a \n test", then after your replacement the memory would look like this:"this \0 is \0 a \0 test". Most C programs will simply interpret this as the string"this "and ignore everything after the first null.EDIT
As other have pointed out, there are also other problems with your code. sizeof() will return the size of the character pointer, not the length of the string. It is also not possible to modify a readonly string literal.