#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;
}
C语言:返回传入字符串的长度
最新推荐文章于 2023-06-19 15:32:11 发布