わびさびサンプルソース

WindowsやHTML5などのプログラムのサンプルコードやフリーソフトを提供します。

string中の特定文字列をstringで置換する

stringの置き換えを行うには、replaceを使用します。

#include <stdio.h>
#include <tchar.h>
#include <locale.h>
#include <string>
#include <iostream>



/*
	string中の特定文字列をstringで置換する
*/
std::string ReplaceString
(
	  std::string String1	// 置き換え対象
	, std::string String2	// 検索対象
	, std::string String3	// 置き換える内容
)
{
    std::string::size_type  Pos( String1.find( String2 ) );

    while( Pos != std::string::npos )
    {
        String1.replace( Pos, String2.length(), String3 );
        Pos = String1.find( String2, Pos + String3.length() );
    }

    return String1;
}



int _tmain
(
	  int argc
	, _TCHAR* argv[]
)
{
	// 標準出力にユニコード出力する
	setlocale( LC_ALL, "Japanese" );

	// stringをstringで置換する
	std::string str = ReplaceString(
			  "ABCDEFG"
			, "D"
			, "あいうえお"
		);

	// 標準出力へ出力する
	std::cout << str << std::endl;

	// 正常終了
	return( 0 );
}

実行結果

ABCあいうえおEFG






わびさびサンプルソース

WindowsやHTML5などのプログラムのサンプルコードやフリーソフトを提供します。