c - C中遍历字符串中的字符进行分析

标签 c arrays char

好的,方法 myName()是完全错误的。我是 C 编码新手。不知何故,我需要遍历字符串 *theName这样我就可以评估其中的每个字符。我需要在保持char *name[1] = {David $ MN % Baez}的同时做到这一点作为歌曲索引数组。帮助我被困住了!

 #include <stdio.h>


int main()
{
    char *name[1] = {"David $ MN % Baez"} ; // should work

    myName(name) ;  
    return 0 ;
}
void myName(char *theName)
{
    for(int i = 0; i < sizeof(theName); i++)
    {
        if("aeiouAEIOU".IndexOf(theName) >= 0)/////// is vowel
        {
             printf("character [ %c ] located at position %d is a vowel", theName[i], i);
        }


        if(theName == ' ')//////
        {
            printf("character [ %c ] located at position %d is a space", theName[i], i);
        }

        else if(theName == '$' || theName == '%')/////////////////////
        {
            printf("character [ %c ] located at position %d is a symbol", theName[i], i);
        }

        else
        {
            printf("character [ %c ] located at position %d is a consonant", theName[i], i);
        }

    }
}

最佳答案

几个问题:

  1. char *name[1]char * 的数组,有点像 char name[10][1] 但可以动态分配。根据你的描述我 认为你只需要一维数组,所以只使用 char *char[]就可以了。
  2. sizeof 运算符用于查询对象或类型的大小,如果您 如果想要获取字符串的长度,请使用 strlen
  3. 我不知道IndexOf来自哪里,也许其他语言有 这个方法,但是在C中没有。在你的代码中 if("aeiouAEIOU".IndexOf(theName),我想您想查找是否 字符是元音。尝试使用 string.h 中的一些 API。
  4. for (int i=0; ... 这是C++语法,在C中,定义变量out 用于
  5. printf 中使用 \n 来格式化输出。

代码供您引用:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void myName(char *theName);
int main()
{
    char name[] = {"David $ MN % Baez"} ; // should work

    myName(name) ;
    return 0 ;
}
void myName(char *theName)
{
    char vowel[] = "aeiouAEIOU";
    int i=0;
    for(i = 0; i < strlen(theName); i++)
    {
        if(strchr(vowel, theName[i]))/////// is vowel
        {
             printf("character [ %c ] located at position %d is a vowel\n", theName[i], i);
        }


        if(theName == ' ')//////
        {
            printf("character [ %c ] located at position %d is a space\n", theName[i], i);
        }

        else if(theName == '$' || theName == '%')/////////////////////
        {
            printf("character [ %c ] located at position %d is a symbol\n", theName[i], i);
        }

        else
        {
            printf("character [ %c ] located at position %d is a consonant\n", theName[i], i);
        }

    }
}

关于c - C中遍历字符串中的字符进行分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22830398/

相关文章:

c++ - 与教科书上关于unsized array initialization C++的句子混淆

c - 分离和退出线程的内存错误和泄漏?

c - 在没有内联汇编的情况下将 SSE 指令与 gcc 一起使用

javascript - 如何使用 javascript/jquery 获取数组中选中和未选中的复选框值

javascript - 对象数组返回最近日期的最高总值

c - C 中的数组不起作用

c - 输入带有不可打印字符的字符串

java - Anagrams - 我怎样才能通过以下两个测试用例

c - 创建子进程时出现此输出的原因是什么?

c - 验证无向图是否有环