用C语言写一个程序,输入一个字符串,过滤此串,只保留字符串中的字母字符,并统计新生成的字符串中包含的字母个数,要求用指针实现。
将字母字符放到字符串开头位置就行
#include <stdio.h>
int strfun(char *s)
{
char *q = s;
int count = 0;
while(*s != '\0')
{
if((*s >= 'a' && *s <='z') || (*s >= 'A' && *s <='Z'))
{
*q = *s;
q++;
count++;
}
s++;
}
*q = 0;
return count;
}
int main()
{
char s[1000];
gets(s);
int count = strfun(s);
printf("字母字符串为:%s,字母数量为:%d",s,count);
}
#include <stdio.h>
#define MAX_LENGTH 100
int main(void)
{
char original_str[MAX_LENGTH];
char filtered_str[MAX_LENGTH];
char *p_original = original_str;
char *p_filtered = filtered_str;
int count = 0;
printf("请输入一个字符串:");
fgets(original_str, MAX_LENGTH, stdin);
while (*p_original != '\0')
{
if ((*p_original >= 'a' && *p_original <= 'z') ||
(*p_original >= 'A' && *p_original <= 'Z'))
{
*p_filtered = *p_original;
p_filtered++;
count++;
}
p_original++;
}
*p_filtered = '\0';
printf("过滤后的字符串为:%s
", filtered_str);
printf("新字符串中包含的字母个数为:%d
", count);
return 0;
}
具体解释可以参考我这篇文章:https://blog.csdn.net/weixin_43576565/article/details/131062047
#include <stdio.h>
#include <ctype.h>
int filterLetters(char *str);
int main() {
char str[100];
printf("请输入一个字符串: ");
fgets(str, 100, stdin); // 获取用户输入的字符串
int letters_count = filterLetters(str); // 调用函数过滤字母字符并统计个数
printf("过滤后的结果为: %s\n", str);
printf("过滤后的字符串中包含 %d 个字母\n", letters_count);
return 0;
}
int filterLetters(char *str) {
char *p1 = str, *p2 = str;
int count = 0;
while (*p2 != '\0') {
if (isalpha(*p2)) { // 判断字符是否为字母
*p1++ = *p2; // 指针 p1 和 p2 分别指向相同的字母字符
count++; // 统计字母个数
}
p2++; // p2 每次移动指向下一个字符
}
*p1 = '\0'; // 将 p1 所在的位置赋值为 NULL,结束字符串
return count;
}
不知道你这个问题是否已经解决, 如果还没有解决的话:(如果有说错的地方,欢迎留言指正哦~)
### 解决方案
以下是C语言的代码实现:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char s[100];
char *p = s;
int count = 0;
printf("请输入一个字符串:");
scanf("%s", s);
while (*p != '\0') {
if (isalpha(*p)) { // 如果是字母
printf("%c", *p); // 输出该字符
count++; // 统计字母的个数
}
p++; // 移动指针
}
printf("\n过滤后的字母个数:%d\n", count);
return 0;
}
代码解释:
char s[100]
,用来存储用户输入的字符串。char *p = s
,指向该字符数组的首地址。int count = 0
,用来记录过滤后的字母个数。printf
函数提示用户输入字符串,并通过scanf
函数接收用户输入。while
循环遍历字符串中的每一个字符。isalpha(*p)
函数返回值为真),就输出该字符,同时将计数器加一。p
每次循环完成后移动一个字符的位置。这样,我们就通过指针实现了字符串过滤,并成功统计了过滤后的字母个数。
```