字串替換,php字串替換

來源:互聯網
上載者:User

字串替換,php字串替換

                              字串替換

寫一個字串替換函數,如母串"123123123123",把母串中的子串"123",替換為"12345",或者"12"。

思路:

利用庫函數strstr(),定位子串。使用strcpy()進行替換。不斷重複著定位和替換操作,直到定位到NULL為止。


範例程式碼:

#include <stdio.h>#include <stdlib.h>#include <string.h>/*字串替換把字串str中的子串s1,替換成s2*/char *strReplace(char *str, char *s1, char *s2){//在堆中申請一片空間char *s = malloc(50);//清空memset(s, 0, 50);//把str拷貝到s中strcpy(s, str);char buf[50];char *pStr = strstr(s, s1);while (pStr){//儲存後序內容strcpy(buf, pStr+strlen(s1));//s2替換s1strcpy(pStr, s2);//移動pStrpStr += strlen(s2);//把後序內容補上strcpy(pStr, buf);//尋找下一次替換的位置pStr = strstr(pStr, s1);}str = s;return str;}void main(){//"123"->"12345"char *str = "123123123123";printf("原字串\n");printf("%s\n", str);str = strReplace(str, "123", "12");printf("替換後\n");printf("%s\n", str);free(str);system("pause");}
運行







JAVA中用replace函數替換字串,列印輸出的代碼,怎寫??

public String getStr(String aa,String bb)
{
String str="abcdefg"
String str1=str1.replace(aa,bb);//aa是被替換的字串,bb是要替換成的內容
return str;
}

如果有什麼疑問,繼續追問
 
C語言替換字串中某個字元的函數

字元替換簡單,字串替換麻煩。
#include<stdio.h>
char * replaceAll(char * src,char oldChar,char newChar){
char * head=src;
while(*src!='\0'){
if(*src==oldChar) *src=newChar;
src++;
}
return head;
}

main()
{
char s[]="21~31~41";
char * p=s;
p=replaceAll(s,'~',',');
printf("%s\n",p);

}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.