【问题标题】:How to delete part of a string in C++如何在 C++ 中删除部分字符串
【发布时间】:2015-05-28 08:41:52
【问题描述】:

我想知道是否有办法在 c++ 中删除部分字符串并将剩余部分保存在变量中。

com是来自用户的输入,(例如:Write myfile

我想从此输入中删除Write,只获取(myfile)用作要创建的文件的名称。 Write 变量包含字符串 (Write)。 Com 是输入,names 是保存文件名的变量。

write.names = com - write.Writevariable;

【问题讨论】:

    标签: c++ string operators


    【解决方案1】:
    #include <string>
    #include <iostream>           // std::cout & std::cin
    using namespace std;
    
    int main ()
    {
      string str ("This is an example phrase.");
      string::iterator it;
    
      str.erase (10,8);
      cout << str << endl;        // "This is an phrase."
    
      it=str.begin()+9;
      str.erase (it);
      cout << str << endl;        // "This is a phrase."
    
      str.erase (str.begin()+5, str.end()-7);
      cout << str << endl;        // "This phrase."
      return 0;
    }
    

    你可以获取位置并删除一个字符串。

    【讨论】:

      【解决方案2】:

      你可以使用string::erase()方法

      【讨论】:

        【解决方案3】:

        使用std::string::substr 删除部分字符串。

        std::string names = com.substr( write.length() );
        

        正如其他答案中提到的,您也可以使用std::string::erase,但它需要在其他变量中额外复制一份。用法:

        std::string names(com);
        names.erase(0, write.length());
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-04-19
          • 1970-01-01
          • 2017-07-02
          • 2012-01-21
          相关资源
          最近更新 更多