如何获得字符串字符的正确索引?

时间:2016-05-05 22:39:40

标签: c++ arrays

写一个函数接收一个字符串和一个要在字符串中搜索的字符。如果搜索字符存在于数组中,则此函数函数返回搜索字符的索引;如果不存在,则返回-1。此外,如果数组包含多个出现的字符,它将返回最左侧出现的索引。例如,如果字符串是“abab”而搜索字符是'b',则函数返回1;而如果字符是'c',则函数返回-1。 使用任何C ++库函数编写函数。

以下是我的功能。

int indexOf(const char str[], char ch)
{
    int search;
    for (int i = 0; i<20; i++)
    {
        if (ch = str[i])
            search ==i;
        else
            search =-1;

    }
    return search;
}

我的问题是当我输入搜索字符或数组中不存在的字符时,我一直得到19(20-1)。谁能告诉我如何修改我的代码以获得正确的答案?

3 个答案:

答案 0 :(得分:2)

if (ch = str[i])应为if (ch == str[i]),目前您正在执行ch的任务。

并且search ==i正在进行比较,它应该是search = i;所以这是第一个相反的问题。

答案 1 :(得分:1)

我这样做的方式是:

int indexOf(const char str[], int size, char ch)
{
    for (int i = 0; i<size; i++)
    {
        if (str[i] == '\0')
            return -1;
        else if(str[i] == ch)
            return i;
    }
    return -1;
}

该方法的优点是,在以前发现字符串的其余部分时不会浪费时间搜索。

答案 2 :(得分:0)

你犯了一些错误。 if(ch = str [i]) if(ch == str [i]) search == i; 应为 search = i;

并且,如果传递以null结尾的字符串,则无需使用arr的大小。

你可以这样试试。

int indexOf(const char str[], char ch)
{
    for (int idx = 0; str[idx]; idx++)
    {
        if (str[idx] == ch)
            return idx;
    }
    return -1;
}
相关问题