c - 逐个删除单词中的元音
问题描述
我必须编写一个程序,从一个单词中一个一个地删除元音。这意味着它按字母顺序获取每个元音,如果该元音在单词中,它将删除其所有外观,然后打印该单词。然后它对所有其他元音执行此操作。例如,对于单词programming
,输出将是:
progrmming
progrmmng
prgrmmng
同样,如果一个元音有多个出现,它的所有出现都会在一个“步骤”中删除。这是我尝试过的:
#include<stdio.h>
#include<string.h>
int main(){
char word[100],vowels[]={'a','e','i','o','u'},result[100];
int n,nv=sizeof(vowels)/sizeof(char),d=0;
fgets(word,100,stdin);
n=strlen(word);
for(int j=0;j<nv;j++){
for(int i=0;i<n;i++)
{
if (strcmp(&vowels[j], &word[i]) != 0) {
result[i] = word[i];
d++;
}
}
result[d]='\0';
printf("%s",result);
}
}
我知道这段代码不好,它不能正确解决问题,但它至少应该正确地进行第一次更改,而是保持单词不变。我在 Clion 中使用了调试器,即使当前字母和元音相同,它似乎也会strcmp
返回......-1
解决方案
您需要使用两个指针(源和目标)将字符串复制到其自身(就地),这两个指针对字符串进行迭代。
如果当前字符是当前元音,则什么也不做。否则,将 char 复制到目标指针 [递增]。源指针在每次迭代时递增。
这是一些示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void
novow(char *str)
{
char *dst;
const char *src;
const char *vowel = "aeiou";
// show the original string
printf("%s\n",str);
// eliminate all vowels in order
for (int vow = *vowel++; vow != 0; vow = *vowel++) {
dst = str;
src = str;
// copy over chars one-by-one
int clip = 0;
for (int chr = *src++; chr != 0; chr = *src++) {
// char is vowel -- skip it but remember that we saw it
if (chr == vow)
clip = 1;
// not the current vowel -- copy it over
else
*dst++ = chr;
}
*dst = 0;
// show the changed string
if (clip)
printf("%s\n",str);
}
}
void
dotest(const char *str)
{
char *buf = strdup(str);
novow(buf);
free(buf);
}
int
main(int argc,char **argv)
{
--argc;
++argv;
int sep = 0;
for (; argc > 0; --argc, ++argv) {
if (sep)
printf("\n");
sep = 1;
dotest(*argv);
}
return 0;
}
对于以下论点:
quick brown fox jumps over the lazy dogs booking
这是输出:
quick
quck
qck
brown
brwn
fox
fx
jumps
jmps
over
ovr
vr
the
th
lazy
lzy
dogs
dgs
booking
bookng
bkng
更新:
如果我们比较最终的源指针和目标指针是否相等,我们可以消除clip
上面的额外变量:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void
novow(char *str)
{
char *dst;
const char *src;
const char *vowel = "aeiou";
// show the original string
printf("%s\n",str);
// eliminate all vowels in order
for (int vow = *vowel++; vow != 0; vow = *vowel++) {
dst = str;
src = str;
// copy over chars one-by-one
for (int chr = *src++; chr != 0; chr = *src++) {
// not the current vowel -- copy it over
if (chr != vow)
*dst++ = chr;
}
*dst++ = 0;
// show the changed string
if (dst != src)
printf("%s\n",str);
}
}
void
dotest(const char *str)
{
char *buf = strdup(str);
novow(buf);
free(buf);
}
int
main(int argc,char **argv)
{
--argc;
++argv;
int sep = 0;
for (; argc > 0; --argc, ++argv) {
if (sep)
printf("\n");
sep = 1;
dotest(*argv);
}
return 0;
}
推荐阅读
- git - Git rebase:使用合并而不是 rebase 解决冲突
- c# - 有没有办法在运行时根据用户选择的特定表动态创建模型
- python - get_object_or_404 can't find object with primary key
- javascript - Angular中的窗口聚焦过程
- excel - 当 Excel 中的数据源更新时,电源查询运行后硬编码的值错位
- html - 隐藏在 Angular 中无法使用 Array
- r - 在R数据帧中减去对角线?
- smartgit - 如何让 SmartGit 一次只显示一个存储库?
- c++ - 如何在 C++ 中返回没有模板的泛型类型?
- javascript - 利用 localStorage 的简单无线电形式在移动设备上不起作用