簡體   English   中英

如何在C ++中從字符串中刪除字符?

[英]How do I remove a character from a string in c++?

我需要調試我的代碼的幫助。 我已經嘗試了很多事情,但是似乎無法從字符串中刪除字符。

我也不太了解std :: erase的工作原理,不確定是否可以用它擦除字符。

#include <iostream>
#include <string>

using namespace std;
int main(){

    string s;
    char n;
    cin >> s;
    cin >> n;

    for (int i = 0;i < s.length(); i++) {
        s.erase (n[i]);
    }

    cout << s;

    return 0;

}

編輯:抱歉,如此含糊。 我意識到了嘗試從數組而不是預期的字符串中刪除某些內容的問題。 借助已發布的答案; 下面附有更新的代碼,該代碼以我想要的方式工作。 謝謝您的反饋!

#include <iostream>
#include <string>

using namespace std;
int main(){

string s;
char n;
cin >> s;
cin >> n;

for (int i = 0; i < s.length(); i++) {
    while (s[i] == n) {
      s.erase(i, i);
    }
}

cout << s;

return 0;

}

使用擦除刪除慣用語

#include <iostream>
#include <string>
#include <algorithm>

int main() {

    std::string s = "Hello World!";
    s.erase(std::remove(s.begin(), s.end(), 'l', s.end());
    std::cout << s << std::endl;
    return 0;
}

分解為兩個語句將是:

#include <iostream>
#include <string>
#include <algorithm>

int main() {

    std::string s = "Hello World!";
    auto it = std::remove(s.begin(), s.end(), 'l');
    s.erase(it, s.end());
    std::cout << s << std::endl;
    return 0;
}

如果只想從字符串中刪除一個字符,則可以使用它的方法find在字符串中找到該字符。 例如

auto pos = s.find( n );
if ( pos != std::string::npos ) s.erase( pos, 1 );

或者您可以通過以下方式使用循環

std::string::size_type pos = 0;

while ( pos < s.size() && s[pos] != n ) ++pos;

if ( pos != s.size() ) s.erase( pos, 1 );

如果要使用循環擦除字符串中所有出現的字符,可以編寫

for ( std::string::size_type pos = 0; pos < s.size(); )
{
    if ( s[pos] == n ) s.erase( pos, 1 );
    else ++pos;
} 

如果您對要執行的操作進行了適當的描述,將很有幫助。 這個問題有點含糊,但是我想您正在嘗試從字符串中刪除給定的char,如果這是您要嘗試的操作,那么這是一個基於您已經提供的工作示例。

#include <iostream>
#include <string>

using namespace std;
int main(){

    string s;
    char n ;

    cin >> s;
    cin >> n;
    for (int i = 0; i < s.length(); i++) {
        if (s[i] == n) {

          s.erase(i, 1);

        }           
    }

    cout << s;

    return 0;

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM