字符串操作

首先,

#include <string>

删除字符串中某一项

删除字符串第0项

#include <iostream>
#include <string>

int main ()
{
    std::string str ("This is an example sentence.");
    std::cout << str << '\n';
    str.erase(str.begin()+0);
    std::cout<<str;
    return 0;
}
This is an example sentence.
his is an example sentence.

删除字符串第5项(从0开始)

#include <iostream>
#include <string>

int main ()
{
    std::string str ("This is an example sentence.");
    std::cout << str << '\n';
    str.erase(str.begin()+5);
    std::cout<<str;
    return 0;
}
This is an example sentence.
This s an example sentence.

删除字符串第7项后8个字符串(从0开始)

#include <iostream>
#include <string>

int main ()
{
    std::string str ("This is an example sentence.");
    std::cout << str << '\n';
    str.erase (7,8);
    std::cout<<str;
    return 0;
}
This is an example sentence.
This isple sentence.

删除 从开头5个字符 到 倒数7个字符 之间的字符

#include <iostream>
#include <string>

int main ()
{
    std::string str ("This is an example sentence.");
    std::cout << str << '\n';
    str.erase (str.begin()+5, str.end()-7);
    std::cout<<str;
    return 0;
}
This is an example sentence.
This ntence.

最后更新于

这有帮助吗?