如何在C ++中删除部分字符串

问题描述 投票:-20回答:3

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

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

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

write.names = com - write.Writevariable;
c++ string operators
3个回答
3
投票
#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()方法


0
投票

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

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

如其他答案所述,您也可以使用std::string::erase,但在其他变量中需要额外的副本。用法:

std::string names(com);
names.erase(0, write.length());
© www.soinside.com 2019 - 2024. All rights reserved.