1. 程式人生 > >C/C++中進行字串的替換、刪除、右移

C/C++中進行字串的替換、刪除、右移

一、關於在C++中如何使字串進行替換的程式碼

#include <iostream>
#include <string>
using namespace std;
void string_replace( string &strBig,  const string &strsrc,  const string &strdst)
{
    string::size_type pos = 0; //替換字串的位置
    string::size_type srclen = strsrc.size();//替換字串的長度
    string::size_type dstlen = strdst.size();//目的字串的長度
    
    while( (pos=strBig.find(strsrc, pos)) != string::npos )
    {
        strBig.replace( pos, srclen, strdst );
        pos += dstlen;
    }
}

int main(int argc, char*argv[])
{
    string strContent = "This is a Test";

    string_replace(strContent, "Test", "demo");

    cout << strContent << endl;

    return 0;
}

二、關於在C語言中進行指定字元進行刪除

#include <stdio.h>
char   *deleteChar  (char *str,char c)
{
    char *head = NULL;
    char *p = NULL;

    if(str ==NULL)
    {
        return NULL;
    }
    head = p = str;
    while(*p++)
    {
        if(*p != c)
        {
            *str++ = *p;
        }
    }
    *str = '\0';
    return head;
}
int main()
{
    char string[] = "cabcdefcgchci";
    char c = 0;
    scanf("%c",&c);  //輸入c
    printf("%s\n",string);
    deleteChar(string,c);
    printf("%s\n",string); //abdefghi
    return 0;
}

三、c語言中進行字元右移

#include <stdio.h>
#include <string.h>
#include <assert.h>

 //實現字串的右移兩位

void RightLoopMove(char *pStr, unsigned short steps) 
{
    int i = 0;
    int len = strlen(pStr);  //字串的長度
    assert(pStr); //判斷如果它的條件返回錯誤,則終止程式執行
    for (i = 0; i < steps; i++)
    {
        char *pend = pStr + len - 1;
        char tmp = *(pStr + len - 1);
        while (pStr <= pend)
        {
            *pend = *(pend - 1);
            pend--;
        }
        *pStr = tmp;
    }
}

int main()
{
    char str[] = "abcdef";
    RightLoopMove(str, 2);//進行右移兩位
    printf("%s\n", str);
    getchar();
    return 0;
}