[英]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.