[英]Pointers/C-Strings in C++. How to filter the strings?
我有一個數組來過濾。
例:
str = "hellothere"
和filter = "eo"
。 我需要過濾時該怎么辦?
void filter_str(char* str, char* filter, char*result)
{
while(*str)
{
if() //If the current character in str is one to be filter.
{
*str++;
}
else
{
*result++ = *str++;
}
}
*result = '\0';
}
我只是無法弄清楚如何檢查當前字符是否需要過濾。 由於過濾器可以有多個字符,例如“eo”。 如何在每個循環中檢查“e”和“o”,然后在開始時將過濾器重置為“e”。
我想制作一個指向過濾器開始的指針,然后在結束時使用它來返回過濾器的開始。 但我不知道如何檢查* str來反對所有要過濾的字符。
在這種情況下,已經編寫了一個函數,可以為您完成艱苦的工作
if (strchr(filter, *str))
一般來說,這是您處理過於復雜而無法處理的任何問題的答案。 編寫一個函數來解決“內部”問題,然后在“外部”問題中使用該函數。 在這種情況下,內部問題是在字符串中查找字符,外部問題是您正在執行的過濾操作。 你很幸運,內心問題已經為你解決了。
如果你想知道一個字母是否在filter
,“簡單”的方式(不使用STL函數)將循環遍歷filter
的元素並檢查它們中的每一個,看看你是否找到了你正在尋找的字符。
while(*str)
{
bool found = false;
// For each element in filter {
// If *str == element {
found = true;
break; // This function gets you out of the 'for' loop
}
}
if(found) //If the current character in str is one to be filter.
{
您可以在評論中填寫偽代碼
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.