[英]Remove vowels from string C++
所以我是 C++ 的新手,並試圖創建一個函數來從字符串中刪除元音,但我失敗了,這是我目前的代碼:
#include <string>
using namespace std;
string remove(string st) {
for(int i = 0; st[i] != '\0'; i++)
st[i] = st[i] == 'a' || st[i] == 'e' || st[i] == 'i' || st[i] == 'o' || st[i] ==
'u' || st[i] == 'A' || st[i] == 'E' || st[i] == 'I' || st[i] == 'O' || st[i] ==
'U' ? '' : st[i];
}
return st;
這似乎引發錯誤? 知道我做錯了什么
我得到的錯誤是:
main.cpp:10:16: error: expected expression 'U' ? '' : Z[i];
並在另一個解釋器上運行:
.code.tio.cpp:7:14: error: incompatible operand types ('const char *' and '__gnu_cxx::__alloc_traits<std::allocator<char>, char>::value_type' (aka 'char'))
'U' ? "" : Z[i];
^ ~~ ~~~~
根據謂詞(條件)從順序容器中刪除元素的規范方法是使用std::remove_if
。 不像它的名字暗示的那樣,這個標准算法並沒有完全刪除元素,它將它們移動到容器的后面,這樣它們就很容易擦除,而其他元素則保持不變並保持相同的順序。 它返回一個迭代器,指示包含“已刪除”元素的容器部分的開始。 由於標准算法無法更改它們操作的容器的大小,因此必須使用容器的適當 remove 方法刪除這些元素。 在std::string
的情況下,就是std::string::erase
。
std::remove_if
接受一對定義要檢查的元素范圍的迭代器,以及一個用於確定要刪除哪些元素的謂詞。 刪除謂詞為true
元素。
#include <algorithm>
#include <iostream>
#include <string>
// Returns true if p_char is a vowel
bool is_vowel(const char p_char)
{
constexpr char vowels[] = { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' };
return std::find(std::begin(vowels), std::end(vowels), p_char) != std::end(vowels);
}
std::string remove_vowel(std::string st)
{
// Moves all the characters for which `is_vowel` is true to the back
// and returns an iterator to the first such character
auto to_erase = std::remove_if(st.begin(), st.end(), is_vowel);
// Actually remove the unwanted characters from the string
st.erase(to_erase, st.end());
return st;
}
int main()
{
std::cout << remove_vowel("Hello, World!");
}
''
不是有效字符,您不能將“空”字符(C++ 中不存在這種東西)放入字符串中以刪除內容...
您可以做的是將非元音(即輔音)移到前面,跳過元音,然后刪除末尾的多余字符:
auto pos = st.begin();
for(auto c : st)
{
if(isConsonant(c))
*pos++ = c;
}
st.erase(pos, st.end());
編輯:正如弗朗索瓦(正確地)表示:沒有必要重新發明輪子(前提是您不被禁止使用標准庫):
st.erase(std::remove_if(st.begin(), st.end(), [](char c) { return isConsonant(c); }), st.end());
請注意, std::remove_if
(以及std::remove
)通過僅將元素移動到保留的前面並將迭代器返回到數據的新末尾來“刪除” - 但並沒有真正刪除“后面”的元素新的結束。 因此有必要如上所示明確erase
它們。
因此,我是C ++的新手,並試圖創建一個可以從字符串中刪除元音的函數,但是我卻很失敗,這是到目前為止的代碼:
#include <string>
using namespace std;
string remove(string st) {
for(int i = 0; st[i] != '\0'; i++)
st[i] = st[i] == 'a' || st[i] == 'e' || st[i] == 'i' || st[i] == 'o' || st[i] ==
'u' || st[i] == 'A' || st[i] == 'E' || st[i] == 'I' || st[i] == 'O' || st[i] ==
'U' ? '' : st[i];
}
return st;
這好像拋出一個錯誤? 不知道我在做什么錯
我得到的錯誤是:
main.cpp:10:16: error: expected expression 'U' ? '' : Z[i];
並在另一個解釋器上運行:
.code.tio.cpp:7:14: error: incompatible operand types ('const char *' and '__gnu_cxx::__alloc_traits<std::allocator<char>, char>::value_type' (aka 'char'))
'U' ? "" : Z[i];
^ ~~ ~~~~
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.