2013-02-11 211 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