如何在C++中删除字符串的一部分
How to delete part of a string in C++
我想知道是否有办法在c++中删除字符串的一部分并将剩余部分保存在变量中。
com
是用户的输入,(例如:Write myfile
)
我想从此输入中删除 Write
以仅获取 (myfile
) 用作要创建的文件的名称。 Write
变量包含字符串 (Write
)。 Com
是输入,names
是保存文件名的变量。
write.names = com - write.Writevariable;
使用std::string::substr
删除部分字符串。
std::string names = com.substr( write.length() );
正如其他答案中提到的,您也可以使用 std::string::erase
,但它需要在其他变量中进行额外的复制。用法:
std::string names(com);
names.erase(0, write.length());
你可以使用string::erase()方法
#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;
}
你可以获取位置并删除一个字符串。
我想知道是否有办法在c++中删除字符串的一部分并将剩余部分保存在变量中。
com
是用户的输入,(例如:Write myfile
)
我想从此输入中删除 Write
以仅获取 (myfile
) 用作要创建的文件的名称。 Write
变量包含字符串 (Write
)。 Com
是输入,names
是保存文件名的变量。
write.names = com - write.Writevariable;
使用std::string::substr
删除部分字符串。
std::string names = com.substr( write.length() );
正如其他答案中提到的,您也可以使用 std::string::erase
,但它需要在其他变量中进行额外的复制。用法:
std::string names(com);
names.erase(0, write.length());
你可以使用string::erase()方法
#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;
}
你可以获取位置并删除一个字符串。