您的位置:首页 > 编程语言 > C语言/C++

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

2017-07-25 20:29 288 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐