日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C語言實現字符串替換的示例代碼_C 語言

作者:bufanq ? 更新時間: 2022-03-26 編程語言

?替換,意思就是用另一個字符串str3來替換str1中所有的str2。替換過程和查找的過程可以合并在一起,在上面循環查找的過程中,每找到一個str2,就把它替換為str3,替換后移動指針p。替換的情況分好幾種:一種是str2和str3的長度相同,一種是str3比str2長,一種是str3比str2短。第一種情況比較簡單,直接使用strncpy函數就可以,后面兩種情況,都需要把str1中的元素進行移動。比如,在上面的例子中,str2=“the”,假設str3 =“this”,str3比str2長,為了有足夠的空間,每找到一個the,從the后面的字符開始到結尾的‘\0’都要往后移動1個字節,也就是給this騰出4個字節的地方來(the的3個字節加移出來的1個字節)。假設str3 =“ok”,str3比str2短,為了填補空缺,每找到一個the,從the后面的字符開始到結尾的‘\0’都要往前移動1個字節,也就是給ok留出兩個字節的地方就夠了。移動過后,使用strncpy函數把str3拷貝到str2所在的地方。下面的程序中,str_replace就是用來實現替換功能的。

關鍵點:

注意字符數組與字符串的區別;在字符數組最后一個字符后面加上’\0’就構成了一個字符串。

/*-------------------------------------------------
功能:實現字符串的替換
描述:第一行輸入原字符串,第二行輸入要替換字符串,
第三行輸入新的字符串
輸入示例:
There is an orange, do you want to eat it?
orange
apple
輸出示例:
There is an apple, do you want to eat it?
Author: Zhang Kaizhou
Date: 2019-8-9 11:11:32
--------------------------------------------------*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 300

void str_replace(char * str1, char * str2, char * str3);

int main(){
? ? char str1[MAXSIZE];
? ? char str2[MAXSIZE];
? ? char str3[MAXSIZE];
? ? gets(str1);
? ? gets(str2);
? ? gets(str3);
? ? str_replace(str1, str2, str3);
? ? puts(str1);

? ? return 0;
}

void str_replace(char * str1, char * str2, char * str3){
? ? int i, j, k, done, count = 0, gap = 0;
? ? char temp[MAXSIZE];
? ? for(i = 0; i < strlen(str1); i += gap){
? ? ? ? if(str1[i] == str2[0]){
? ? ? ? ? ? done = 0;
? ? ? ? ? ? for(j = i, k = 0; k < strlen(str2); j++, k++){
? ? ? ? ? ? ? ? if(str1[j] != str2[k]){
? ? ? ? ? ? ? ? ? ? done = 1;
? ? ? ? ? ? ? ? ? ? gap = k;
? ? ? ? ? ? ? ? ? ? break;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? if(done == 0){ // 已找到待替換字符串并替換
? ? ? ? ? ? ? ? for(j = i + strlen(str2), k = 0; j < strlen(str1); j++, k++){ // 保存原字符串中剩余的字符
? ? ? ? ? ? ? ? ? ? temp[k] = str1[j];
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? temp[k] = '\0'; // 將字符數組變成字符串
? ? ? ? ? ? ? ? for(j = i, k = 0; k < strlen(str3); j++, k++){ // 字符串替換
? ? ? ? ? ? ? ? ? ? str1[j] = str3[k];
? ? ? ? ? ? ? ? ? ? count++;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? for(k = 0; k < strlen(temp); j++, k++){ // 剩余字符串回接
? ? ? ? ? ? ? ? ? ? str1[j] = temp[k];
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? str1[j] = '\0'; // 將字符數組變成字符串
? ? ? ? ? ? ? ? gap = strlen(str2);
? ? ? ? ? ? }
? ? ? ? }else{
? ? ? ? ? ? gap = 1;
? ? ? ? }
? ? }
? ? if(count == 0){
? ? ? ? printf("Can't find the replaced string!\n");
? ? }
? ? return;
}

原文鏈接:https://blog.csdn.net/bufanq/article/details/51567454

欄目分類
最近更新