How can I take a C string pointer like
char *a = "asdf";
and change it so that it becomes
char *a = "\nasdf\n";
How can I take a C string pointer like
char *a = "asdf";
and change it so that it becomes
char *a = "\nasdf\n";
When you assign string like tihs
char *a = "asdf";
you are creating a string literal. So it cannot be modified. It is already explained here.
您无法修改字符串文字,因此您必须使用该新格式创建第二个字符串。
或者,如果格式只是为了显示,您可以通过在显示时应用格式来推迟创建新字符串。例如:
printf("\n%s\n", a);
我不知道这是否是您正在寻找的,但看起来您想要连接字符串:如何在 C 中连接 const/literal 字符串?
使用 "\n" 作为您的第一个和最后一个字符串,并将给出的字符串作为第二个字符串。
如果您使用指向字符串文字的指针,则不能这样做,原因是字符串文字是常量且无法更改。
你可以做的是声明一个数组,有足够的空间来容纳额外的字符,比如
char a[16] = "asdf";
然后您可以例如memmove
移动字符串,并手动添加新字符:
size_t length = strlen(a);
memmove(&a[1], a, length + 1); /* +1 to include the terminating '\0' */
a[0] = '\n'; /* Add leading newline */
a[length + 1] = '\n'; /* Add trailing newline */
a[length + 2] = '\0'; /* Add terminator */
char* a = "asdf";
char* aNew = new char[strlen(a) + 2]; //Allocate memory for the modified string
aNew[0] = '\n'; //Prepend the newline character
for(int i = 1; i < strlen(a) + 1; i++) { //Copy info over to the new string
aNew[i] = a[i - 1];
}
aNew[strlen(a) + 1] = '\n'; //Append the newline character
a = aNew; //Have a point to the modified string
希望这就是你要找的。完成后不要忘记调用“delete [] aNew”以防止它泄漏内存。