わびさびサンプルソース

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

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

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

wstring中の特定文字列をwstringで置換する
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>
 
 
 
/*
    wstring中の特定文字列をwstringで置換する
*/
std::wstring ReplaceString
(
      std::wstring String1  // 置き換え対象
    , std::wstring String2  // 検索対象
    , std::wstring String3  // 置き換える内容
)
{
    std::wstring::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::wstring str = ReplaceString(
              L"ABCDEFG"
            , L"D"
            , L"あいうえお"
        );
 
    // 標準出力へ出力する
    std::wcout << str.c_str() << std::endl;
 
    // 正常終了
    return( 0 );
}

実行結果

ABCあいうえおEFG






わびさびサンプルソース

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