其中之一,你不能做你的問題,仍然有他們作爲空終止的字符串工作。這是因爲text
內存佈局是這樣的:
char text_as_array[] = {
'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '.', '\0'
};
通知的'\0'
底。字符數組test
實際上不是長度12,它是長度。
空終止所需的控制檯輸出函數,如printf和std ::法院(C++)的工作:
char good[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
printf("%s\n", good); /* this works, because it is null-terminated */
char bad[] = { 'H', 'e', 'l', 'l', };
printf("%s\n", bad); /* this will print out garbage, or crash your program! */
這意味着你必須定義你這樣的數組:
char one[6];
char two[3];
char three[6];
如果你想少做typi
one[0] = text[7]; /* o */
one[1] = text[8]; /* r */
one[2] = text[9]; /* l */
one[3] = text[10]; /* d */
one[4] = text[11]; /* . */
one[5] = '\0'; /* you have to null-terminate the string */
:
您可以通過手來簡單地複製值超出做到這一點NG,或只是想寫出更好的代碼,你可以利用一個事實,即數組/串是連續的優勢,並使用一個循環來將數據複製過來:
for(int i = 0; i < 5; ++i)
{
one[i] = text[7 + i];
}
one[5] = '\0';
但是,如果你想這是一個非常C中常見的事情,那麼你猜對了。而不是每次手動編碼此循環,您應該使用內置函數爲您進行復制:
/* C uses "", C++ uses <> */
#include "string.h" /* C++: #include<cstring> */
#include "stdio.h" /* C++: #include<cstdio> */
/* don't do "int function(void)", do "int function()" instead */
int main()
{
char *text = "Hello World."; /* string length 12, array size 13 */
/* size of these has to accomodate the terminating null */
char one[6];
char two[3];
char three[6];
/* copy two characters, starting at index 5 */
strncpy(two, &text[5], 2);
/* for three, we don't have to do &text[0], because it is at the beginning of the string */
strncpy(three, text, 5);
/* we can do strcpy if we're at the end of the string. It will stop when it hits '\0' */
strcpy(one, &text[7]);
/* note that we still have to null-terminate the strings when we use strncpy */
two[2] = '\0';
three[5] = '\0';
/* but we don't have to null-terminate when we use strcpy */
/* so we can comment this out: one[5] = '\0'; */
printf("%s\n", one);
printf("%s\n", two);
printf("%s\n", three);
return 0; /* returns 0, since no errors occurred */
}
這沒有任何意義。 「將問候分成三個單詞」意味着什麼? – bmargulies 2010-10-17 22:48:38
這應該是一個通用的答案,或只爲「Hello World」?你已經澄清了你的問題,因爲現在它是模糊的,可能是功課。 – birryree 2010-10-17 22:51:45
爲了減少混淆,我編輯了這個問題,但仍然完全符合他原先的意圖(密切關注他所調用的字符串,爲什麼他會有* 3個變量,如果他顯然只有兩個單詞?)。其他編輯改變了問題的含義,答案不會是他想要的。 – 2010-10-17 23:26:16