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

来源:互联网 发布:加拿大北电网络市值 编辑:程序博客网 时间:2024/05/18 03:55
#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;}
原创粉丝点击