2013-02-11 208 views
0

我如何可以采取一个C字符串的指针一样字符串指针修改

char *a = "asdf"; 

,并改变它,使之成为

char *a = "\nasdf\n"; 
+0

在学习字符串处理之前,你应该仔细研究数组和指针。 – Lundin 2013-02-11 08:40:09

回答

0

当您指定字符串如tihs

char *a = "asdf"; 

你正在创建一个字符串文字。所以它不能被修改。已经解释过here

0

您不能修改字符串文字,因此您将不得不使用该新格式创建第二个字符串。

或者,如果格式仅用于显示,那么您可以在显示格式时应用格式来缓慢创建新字符串。例如:

printf("\n%s\n", a); 
0

如果您使用指向字符串的指针,则不能这样做,原因是字符串常量是不变的,无法更改。

你可以做什么是声明数组,有足够的空间来容纳多余的字符,像

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 */ 
-1
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”来防止它泄漏内存。

+0

-1针对不同编程语言的离题答案。 – Lundin 2013-02-11 08:41:03

+0

可能应该重复检查标记...它的工作原理是C++:P – 2013-02-11 20:12:12