[英]How can I mark the end of a C string?
這是該函數的代碼:
void pattern(char word[200], char asPattern[200]) {
for (unsigned i = 0; i < strlen(word); i++) { // unsigned to remove warning
if (strchr("aeiou", word[i]) != 0) asPattern[i] = '*';
else asPattern[i] = '#';
}
基本上,此函數將單詞中的輔音替換為#,將元音替換為*,並將新模式存儲在asPattern字符串中。 但是,如果我在屏幕上顯示asPattern,它將顯示正確的模式,后跟一堆未知符號(strlen(asPattern)等於211或for循環后的值)。 我認為問題在於,未標記asPattern的結尾,並且asPattern [strlen(asPattern)] ='/ 0'無效,我不知道該怎么辦...
我不能使用std :: string,所以請忍受並使用C字符串。
添加代碼
asPattern[strlen(word)] = '\0';
for循環之前或之后
C字符串以空字符終止,可以用文字0或'\\ 0'表示。 使用C字符串的函數(如strlen)期望得到這種效果。 請注意, strlen()
掃描字符串中的空字符,因此您的循環如下:
for (unsigned i = 0; i < strlen(word); i++)
是無效的strlen()
必須在每次迭代中掃描word
。 因此更好的代碼可能是:
void pattern(char word[200], char asPattern[200]) {
const unsigned len = strlen(word);
for (unsigned i = 0; i < len; i++) { // unsigned to remove warning
if (strchr("aeiou", word[i]) != 0) asPattern[i] = '*';
else asPattern[i] = '#';
}
asPattern[len] = 0; // or '\0' if you prefer
}
最簡單,幾乎萬無一失的解決方案是將整個字符塊設置為\\0
。 假設您已預先了解char數組的實際大小,則此方法可以正常工作。
#include <string.h>
void pattern(char word[200], char asPattern[200])
{
memset(asPattern, '\0', 200); // we are assuming that there really are 200 bytes
//...
}
完成此操作后,就不必擔心空終止符了。
另外,請注意:
void pattern(char word[200], char asPattern[200])
沒什么不同:
void pattern(char* word, char* asPattern)
所以實際上,該函數並不真正知道asPattern
有多大。 再說一次,如果您預先知道大小是多少,並且知道無論如何都會覆蓋該字符串,則只需使用memset
,而不必擔心是否應該使用strlen()
或任何其他方案來計算空字節的去向。
我已經測試了您的功能,並且工作正常。 (以下是代碼段: http : //rextester.com/XDSU30889 )
必須將“ asPattern”發送到從任何內容中清除的函數(它必須充滿'\\0'
0'-s,如果您在Windows上,這就是GlobalAlloc()
功能,否則請使用malloc()
然后memset()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.