C语言:返回传入字符串的长度

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

//返回传入字符串的长度
int GetStrLength(char[]);

//封装fgets,用来接受字符串的字符数组,接受的字符总数
void GetString(char [], int count);
void GetString(char str[], int count)
{
    //使用fgets函数接受字符串,使用\0替换字符数组的最后一位\n
    fgets(str, count, stdin);
    //返回\n字符所在的指针
    char * find = strchr(str, '\n'); //查找换行符
    if(find)//如果找到了
        *find = '\0';   //根据找到的指针,修改指向的元素为\0
}


int GetStrLength(char str[])
{
    int count = 0;//字符串中的字符个数
    int i;
    while(str[count] != '\0')
    {
        if(str[count] == '\n')
        {
            str[count] = '\0';//替换
            break;
        }

        count++;
    }
    return count;
}

int main()
{
    char names1[50];
    //fgets(names1, 5, stdin);

    GetString(names1, 20);
    int len = GetStrLength(names1);
    printf("字符串的长度为: %d\n", len);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值