C 语言实例 – 计算字符串长度

C语言教程评论

C 语言实例 - 计算字符串长度

计算字符串长度。

实例 - 使用 strlen()

#include <stdio.h>
#include <string.h>

int main()
{
    char s[1000];
    int len;

    printf("输入字符串: ");
    scanf("%s", s);
    len = strlen(s);

    printf("字符串长度: %d", len);
    return 0;
}

输出结果为:文章源自公式库网-https://www.gongshiku.com/html/202112/c-yuyanshili-jisuanzifuchuanzhangdu.html

输入字符串: nowcoder
字符串长度: 6

实例 - 不使用 strlen()

#include <stdio.h>

int main()
{
    char s[1000], i;

    printf("输入字符串: ");
    scanf("%s", s);

    for(i = 0; s[i] != '\0'; ++i);

    printf("字符串长度: %d", i);
    return 0;
}

输出结果为:文章源自公式库网-https://www.gongshiku.com/html/202112/c-yuyanshili-jisuanzifuchuanzhangdu.html

输入字符串: nowcoder
字符串长度: 8
文章源自公式库网-https://www.gongshiku.com/html/202112/c-yuyanshili-jisuanzifuchuanzhangdu.html文章源自公式库网-https://www.gongshiku.com/html/202112/c-yuyanshili-jisuanzifuchuanzhangdu.html
运营不易,
感谢支持!
weinxin
我的微信
我的微信公众号
我的微信公众号扫一扫
weinxin
我的公众号
 
公式库网
  • 本文由 公式库网 发表于 2021年12月7日20:47:29
  • 转载请务必保留本文链接:https://www.gongshiku.com/html/202112/c-yuyanshili-jisuanzifuchuanzhangdu.html

发表评论