11.3 字符串和字符数组:缩短数组长度

strlen()函数用于统计字符串的长度
缩短数组长度

#include
#include
void fit(char *, unsigned int);
int main() 
{
    char mesg[] = "thing should be as simple as possible,"
        "but not simpler.";

    puts(mesg);
    fit(mesg, 38);
    puts(mesg);
    puts("let us look at some more of the string.");
    puts(mesg + 39);

    return 0;
}

void fit(char *string, unsigned int size)
{
    if (strlen(string) > size)
        string[size] = '\0';
}

fit()函数把第39个元素的逗号替换成字符'\0',puts()函数在空字符处停止输出,但是这些字符还是在缓冲区,puts(mesg + 39)函数把它打印出来。
mesg + 39 是mesg[39]的地址,put函数持续输出直到遇到原来字符串中的空格。

你可能感兴趣的:(11.3 字符串和字符数组:缩短数组长度)