2

所以我的任务是填写我的函数以使用测试驱动程序,该驱动程序在每次运行期间为其提供随机字符串。对于此功能,我必须将每个单词的第一个字符转换为大写字母,其他所有字符都必须更低。

它大部分都有效,但我的代码遇到的问题是它不会将第一个字符大写,并且如果在这个词之前有一个句点,例如:

。单词

在这种情况下,“w”将保持较低。

这是我的来源:

void camelCase(char line[])
{
    int index = 0;
    bool lineStart = true;

    for (index;line[index]!='\0';index++)
    {
        if (lineStart)
        {
            line[index] = toupper(line[index]);
            lineStart = false;
        }

        if (line[index] == ' ')
        {
            if (ispunct(line[index]))
            {
                index++;
                line[index] = toupper(line[index]);
            }
            else
            {
                index++;
                line[index] = toupper(line[index]);
            }
        }else
            line[index] = tolower(line[index]);
    }
    lineStart = false;

}
4

1 回答 1

3

这是一个应该可行的解决方案,并且在我看来不太复杂:

#include <iostream>
#include <cctype>

void camelCase(char line[])  {
    bool active = true;

    for(int i = 0; line[i] != '\0'; i++) {
        if(std::isalpha(line[i])) {
            if(active) {
                line[i] = std::toupper(line[i]);
                active = false;
            } else {
                line[i] = std::tolower(line[i]);
            }
        } else if(line[i] == ' ') {
            active = true;
        }
    }
}

int main() {
    char arr[] = "hELLO, wORLD!";       // Hello, World!
    camelCase(arr);
    std::cout << arr << '\n';
}

The variable active tracks whether the next letter should be transformed to an uppercase letter. As soon as we have transformed a letter to uppercase form, active becomes false and the program starts to transform letters into lowercase form. If there's a space, active is set to true and the whole process starts again.

于 2016-04-05T20:09:13.613 回答