Search and replace strings

Source: Internet
Author: User

Search and replace strings

Search for the target string in the string and replace it with the specified string. The number of replacement times is returned. The interface is

Int find_str_replace (char * & str, const char * find_str, const char * replace_str)

Replace all find_str in str with replace_str. Do not use STL. The c implementation code is as follows:

# Include
 
  
# Include
  
   
# Include
   
    
// Search for the position int find (const char * str, const char * sub_str, int fromwhere) Where str appears for the first time from fromwhere {int len = strlen (str ); int len_f = strlen (sub_str); for (int I = fromwhere; I
    
     
= Len_f; I ++) {int k = I; int j = 0; while (j
     
      
If c ++ and STL are used, the code is extremely simple:
      

#include
       
        #include
        
         using namespace std;int find_str_replace(string &str,string find_str,string replace_str){int num=0;int len_f=find_str.length();int len_r=replace_str.length();int pos=str.find(find_str,0);while(pos!=string::npos){  str.replace(str.begin()+pos,str.begin()+pos+len_f,replace_str);  pos=pos+len_r;  pos=str.find(find_str,pos);  num++;}return num;}int main(){string a="123456783450987634243453";string b="345";string c="ABCD";int num=find_str_replace(a,b,c);printf("%s\n",a.c_str());printf("%d",num);return 0;}
        
       



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.