c - 使用指针在 C 中查找 char 的索引

标签 c

我在编写一个我被指示编写的程序时遇到了困难。该程序应该搜索出现的第一个元音的单词,然后它应该打印出该元音的索引。如果没有元音字母,则返回 -1。

到目前为止,这是我的代码:

int firstVowel(char* string){
//Variable for case with no vowels
int notInString = -1;
int length = strlen(string);
int i;
for(i = 0; i <= length; i+=1){
    if(*string == 'a' || *string == 'e' || *string == 'i' ||
    *string == 'o' || *string == 'u'){
        return i;
    }
else if(*string != 'a' || *string != 'e' || *string != 'i' || *string != 'o' ||
*string != 'u') {
    return notInString;
}
}
}

当我使用输入“abced”运行它时,它会正确返回 0。但是,当我以 fsed 运行它时,它会错误地返回 -1。

最佳答案

你的循环不会递增string并且总是在第一次比较后返回,你想要

int firstVowel(char* string) {
    //Variable for case with no vowels
    int notInString = -1;
    int length = strlen(string);
    int i;
    for (i = 0; i <= length; i += 1) {
        if (*string == 'a' || *string == 'e' || *string == 'i' ||
            *string == 'o' || *string == 'u') {
            return i;
        } else {
            string++;
        }
    }

    return notInString;
}

这将搜索整个数组,返回它看到的第一个元音的索引。在处理完整个字符串之前,它无法返回 notInString

关于c - 使用指针在 C 中查找 char 的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50032313/

相关文章:

c - 使用正则表达式编写可以验证 URL、IPv4 地址、IPv6 地址和 FQDN 的 C 函数

c++ - 关于将 C++ 类导出到 C 的问题

c - 当我第二次运行该程序时,它没有给我正确的执行时间

c++ - 将 OpenMP 支持添加到使用 Visual Studio 2010 从 C 文件编译的 mex 文件

c++ - 在不知道消息长度之前处理阻塞的 recv() 函数并且不想使用 asy I/O

c - 什么是 WebKitLoadEvent 以及如何获取它以便使用 "load-change"信号回调

c - 一台服务器绑定(bind)不同的端口

c -++ 指针运算符

c++ - Microsoft Media Foundation 与 Directshow 自定义视频过滤器的等效项是什么?

c - 如何从套接字读取无符号字符