わびさびサンプルソース

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

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

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

string中の特定文字列をstringで置換する
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#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などのプログラムのサンプルコードやフリーソフトを提供します。