用c语言利用指针编写程序,统计字符串的长度。(不要使用求字符串长度函数) 输入格式: gets() 输出格式: "The length of the string is %d\n"
时间: 2023-06-17 21:02:07 浏览: 121
下面是一个利用指针计算字符串长度的C语言程序:
```c
#include <stdio.h>
int main() {
char str[100];
char *p = str;
int len = 0;
printf("Enter a string: ");
gets(str);
while (*p != '\0') {
len++;
p++;
}
printf("The length of the string is %d\n", len);
return 0;
}
```
程序首先定义了一个字符数组 `str` 和一个指向字符数组的指针 `p`,并将指针初始化为指向数组的第一个元素。然后使用 `gets()` 函数读取用户输入的字符串。
接下来,程序通过循环遍历字符数组,每遍历一个字符就将计数器 `len` 加一,并将指针向后移动一个位置,直到遍历到字符串的结尾字符 `\0`。
最后,程序输出字符串的长度。注意,输出格式需要使用 `%d` 占位符将计数器 `len` 的值插入到输出字符串中。
相关问题
利用C语言编写程序,统计字符串的长度。(10分) 题目内容:利用指针编写程序,统计字符串的长度。(不要使用求字符串长度函数) 输入格式: gets() 输出格式: "The length of the string is %d\n" 输入样例: I like programming. 输出样例: The length of the string is 19 时间限制:500ms内存限制:32000kb
```c
#include <stdio.h>
int main() {
char str[100];
printf("Please input a string: ");
gets(str);
int len = 0;
char *p = str;
while (*p != '\0') {
len++;
p++;
}
printf("The length of the string is %d\n", len);
return 0;
}
```
编写c语言函数,求给定字符串中数字字符的个数,在主函数中输入字符串及输出统计的个数
下面是一个简单的 C 语言函数,可用于计算给定字符串中数字字符的个数:
```c
#include <stdio.h>
#include <ctype.h>
int countDigits(char *str) {
int count = 0;
while (*str != '\0') {
if (isdigit(*str)) {
count++;
}
str++;
}
return count;
}
int main() {
char str[100];
printf("请输入一个字符串:");
gets(str);
int count = countDigits(str);
printf("字符串中数字字符的个数为 %d\n", count);
return 0;
}
```
该程序首先定义了一个 `countDigits` 函数,该函数使用一个指针遍历字符串,如果指针指向的字符是数字字符,则将计数器加一。最后返回计数器的值。
在主函数中,程序首先提示用户输入一个字符串,然后调用 `countDigits` 函数计算数字字符的个数,并输出结果。