18
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

文字列(string)から特定の文字を削除する方法

Posted at

文字列(string)から空白や特定の文字を削除する方法。


//空白を削除する場合
string testString = " a b c d ";
for(size_t c = testString.find_first_of(" "); c != string::npos; c = c = testString.find_first_of(" ")){
	testString.erase(c,1);
}
printf("%s\n",testString.c_str());

//空白とeを削除する場合
testString = " a eb c ed ";
for(size_t c = testString.find_first_of(" e"); c != string::npos; c = c = testString.find_first_of(" e")){
	testString.erase(c,1);
}
printf("%s\n",testString.c_str());

printfは両方とも
abcd
と出力されるはず。for文の所はwhileで書いた方が見やすいかも(変数cが外に出るのは嫌だけど)。

size_t c;
while((c = testString.find_first_of(" ")) != string::npos){
  testString.erase(c,1);
}
18
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?