文本的最后一个辅音

Last consonant of a text

本文关键字:最后一个 文本      更新时间:2023-10-16

用户输入文本(带空格)后,如何仅删除该文本的最后一个辅音?

我不知道怎么做,不管我现在做了什么,把所有的辅音都删掉了

你尝试过什么吗?或者你不知道怎么做?

我假设你什么也没做。

首先,你必须找到最后一个辅音。你是怎么做到的?嗯,你从结尾开始检查字母,直到你找到一个辅音。现在,当你找到最后一个辅音时,你记住辅音的位置,然后把在辅音右边的每个字母移到左边。最后,将字符串中的最后一个字符更改为''。

代码如下:

#include <iostream>
#include <string>
#include <cctype>
bool isConsonant(char);
int main (int argc, char *argv[]) {
    char s[80];
    // Input the text
    std::cout << "Enter the text: ";
    std::cin.getline(s,80,'n');
    // Creating string object
    std::string text(s);
    int length = text.length();
    // Searching for the last consonant
    int i = length - 1;
    while ((!isConsonant(text.at(i)) && (i)))
        i--;
    // Moving every letter after the last consonant one place to the left
    for (int j = i; j < length - 1; j++)
        text.at(j) = text.at(j+1);
    text.at(length-1) = '';
    // Printing the text to the standard output
    std::cout << text;
    return 0;
}
bool isConsonant(char c) {
    if (isalpha(c)) {   
        char temp = c;
        if (isupper(c))
            temp = tolower(c);
        return !((temp == 'a') || (temp == 'e') || (temp == 'i') || (temp == 'o') || (temp == 'u'));
    }
    return false;
}
编辑:当然还有其他方法可以做到这一点,你应该试着想想。这是我想到的第一件事。