在c ++中测试字符串数组的索引?

时间:2012-03-09 14:11:07

标签: c++ string

#include<iostream>
#include<cstdio>
using namespace std;

int main()
{

    char str[80];
    int i=0;
    cout<<"Enter the String ";
    gets(str);
    for (int j=0;str[j]!='\0';j++)
    if (str[i]=='A'||'E'||'I'||'O'||'U')
    i++;
    cout<<"Number of vowels is: "<<i;



}

这里我是元音字符串中的元素检查元素,有人可以为此建议替代方法吗?我需要计算字符串中的元音数量。

这段代码对我来说非常合适,只需找到替代方法,我不必输入太多“||”和'a'和'A'不同。

6 个答案:

答案 0 :(得分:5)

if (str[i]=='A'||'E'||'I'||'O'||'U') 

这是错误的

应该是这样的:

if(str[i]=='A' || str[i]=='E'||str[i]=='I'||str[i]=='O'||str[i]=='U')

并且还要处理案例敏感性

答案 1 :(得分:4)

str[i]=='A'||'E'||'I'||'O'||'U'

始终返回true,因为'E'始终为true。你正在寻找

strchr("AEIOU", str[j])

注意j,你的循环变量错误了。

(另外,在C ++中,您需要使用iostreamsgetline代替cstdiofgets。)

答案 2 :(得分:2)

更多C ++ - ish解决方案:

std::string vowels("aAeEiIoOuU");
for (int j=0;str[j]!='\0';j++)
{
   if ( vowels.find(str[j]) != std::string::npos )
   i++;
}

答案 3 :(得分:1)

inline bool is_vowel(char a)
{
    a=std::tolower(a);
    switch(a)
    {
    case 'a':        case 'e':
    case 'i':        case 'o':
    case 'u':
        return true;
    }
    return false;
}

int main()
{
    std::string line;
    std::cout << "enter text" << std::endl;
    std::getline(std::cin, line);
    int vowel=std::count_if(line.begin(), line.end(), is_vowel);
    std::cout << "Number of vowels: " << vowel << std::endl;
}

答案 4 :(得分:0)

或使用表格:

#include <iostream>
#include <string>

int main()
{
  char list_v[256] = { 0 };
  list_v['a'] = list_v['e'] = list_v['i'] = list_v['o'] = list_v['u'] = 1;
  list_v['A'] = list_v['E'] = list_v['I'] = list_v['O'] = list_v['U'] = 1;
  std::string str = "a sentence here";
  uint32_t cnt = 0;
  for (uint32_t i = 0; i < str.length(); i++)
     cnt += list_v[str[i]];
  std::cout << "found " << cnt << std::endl;
  return 0;
}

或者使用map用于相同目的,或者使用c ++数组/向量,人们不喜欢这里的c数组。这当然仅适用于ASCII。

答案 5 :(得分:-2)

的方法?还是语法?

我认为这是一个语法错误..它应该像

if(str[i]=='A' || str[i]=='E'||str[i]=='I'||str[i]=='O'||str[i]=='U')

如果你问的是更好的方法,我认为没有... 你正在做O(n)复杂性,这是我猜的好。即使你使用散列,你也必须在字符串中散列所有n个字符..