c - C语言:给定一个字符串,删除/删除包含n个元音的单词
问题描述
给定一个整数n
,程序必须删除每个包含n
元音数量的单词。该字符串是从 test.txt 文件中读取的,该文件包含以下内容:
Astazi nu este maine
. 目前我的程序包含一个count1
函数,它计算字符串中每个单词的字符数和元音数。count1
在输入n
元音以删除所需的单词然后打印更新的字符串时,如何使用函数中的数据作为参考?
我有一个想法,我不确定如何实施。在count1
我们已经计算了每个单词的元音数量,因此,n
由用户给出,我们检查这个数字是否等于函数v
中的count1
,所以我们这样做int num_of_words++
,然后我们执行一个循环,打印出所需的单词,直到num_of_words=0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void count1 (char* str)
{
for (int i = 0;;)
for (int v = 0, w = i;;)
{
int len;
char c = str[i++];
switch (c)
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
v++;
default:
continue;
case ' ':
case '\t':
case '\n':
case '\0':
len = i - 1 - w;
printf("'%.*s': %d characters, %d vowels\n", len, str+w, len, v );
if (c)
break;
else
return;
}
break;
}
}
void count2 (char* str, int n)
{
char line2[128];
int ls=strlen(str);
for (int i = 0;;)
for (int v = 0, w = i;;)
{
int len;
char c = str[i++];
switch (c)
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
v++;
default:
continue;
case ' ':
case '\t':
case '\n':
case '\0':
for(int k = 0; str[k] != '\0'; k++)
{
if (k == 0 || isspace(str[k]))
{
if(v==n)
{
strcat(line2, str+1);
}
}
}
printf("%s ", line2);
if (c)
break;
else
return;
}
break;
}
}
int main()
{
FILE *fp;
char line[128];
int c=0, count[26]= {0}, x;
int n;
fp = fopen("test.txt", "r");
fscanf(fp, "%[^\n]", line);
fclose(fp);
printf("%s\n\n", line);
while (line[c] != '\0')
{
if (line[c] >= 'a' && line[c] <= 'z')
{
x = line[c] - 'a';
count[x]++;
}
c++;
}
for (c = 0; c < 26; c++)
{
printf("%c occurs %d times.\n", c + 'a', count[c]);
}
printf("\n");
count1(line);
printf("\nInsert n: ");
scanf("%d", &n);
count2(line, n);
return 0;
}
解决方案
如果您有一个str
由单独的单词组成的字符串,通过' '
or'\n'
或将一个单词与另一个单词分隔'\t'
,并且您希望拥有一个包含str
满足某些条件的所有单词的字符串,那么对其进行编程以使其将有点困难是“就地”,即更改str
为所需的字符串,而不使用某种“辅助数组”。
相反,我建议创建一个大小相同的新 char 数组(str2
比如你从str
到找到的str2
。
像这样的东西:
char str[128];
// read from file to str using fscanf
char str2[128];
for (int c = 0; str[c] != '\0'; ++c)
{
if (c == 0 || isspace(str[c]))
{
if (! is_1_vowel[str+1]) // if it doesn't have exacly one vowel
{
// copy the word from str to str2
strcat_word(str2, str+1); // a user-defined adapted version of strcat that will copy from src to dest only till src reaches a space character or '\0'
}
}
}
我在这里假设这is_1_vowel
将是一个遍历单个单词(而不是整行或文件)的函数,如果满足条件(有 1 个元音)则返回 1,否则返回 0。
推荐阅读
- javascript - 如何缩放图标背景?
- python - 无法在 pygame.mixer 中打开任何声音文件
- string - 从 Go 中的字符串整数中获取整数切片?
- python-3.x - 您可以在 Google App Engine 的灵活环境中的处理程序元素的脚本设置中指定什么?
- r - 如何根据组获取数据框中变量的最大值行?
- installation - 无法在 Windows 上启动 Nsight Compute 命令行界面
- velocity - 在使用无服务器框架设置 AppSyncAPI 时,是否可以在单个文件中包含多个速度模板?
- angular - 以角度显示 5x5 表格中的数字数组
- javascript - 从A页面点击一个按钮打开一个新的页面B,当关闭页面B时,页面A从B获取一个参数而不刷新。可以吗?
- kotlin - 如何使用 Flutter 和 kotlin 在应用程序之外拥有小部件