1. 程式人生 > >字串替換 eg: str1="123%s456%s" str2={'a','b','c','d'}(將str1中的%s替換成str2中的字元)替換結果返回為:123a456bcd

字串替換 eg: str1="123%s456%s" str2={'a','b','c','d'}(將str1中的%s替換成str2中的字元)替換結果返回為:123a456bcd

//字串替換
//eg: str1=”123%s456%s” str2={‘a’,’b’,’c’,’d’}(將str1中的%s替換成str2中的字元)替換結果返回為:123a456bcd

程式碼塊

#pragma once
#include<iostream>
using namespace std;
#include<assert.h>
#include<string>

void  ReplaceCharacterString(string &str1,int len1, const string str2, int len2)
{
    assert(str1.c_str());
    int
j = 0; int i = 0; for (i = 0; i < len1; ++i) { if (str1[i] == '%') { if (str1[i + 1] == 's') { str1.erase(i, 1);//刪除str1第i個1個字元 --len1; str1[i] = str2[j++]; } } } if (j < len2) { str1.append(str2, j, len2-j);//將str2的剩餘字串追加到str1後
} } void RepCharStrTest() { string str1 = "123%s456%s";//10 //int len1 = strlen(str1.c_str());//法一 int len1 = str1.size();//法二 cout << "原str1: " << str1 <<"長度為:"<<len1<< endl; string str2 = { 'a', 'b', 'c', 'd' };//4 int len2 = strlen(str2.c_str()); cout
<< "原str2: " << str2 << "長度為:" << len2 << endl; ReplaceCharacterString(str1, len1, str2, len2); cout << "替換後的str1: " << str1 << "長度為:" << strlen(str1.c_str()) << endl; }

結果顯示

這裡寫圖片描述