Need A Sample Script For Replace A String

Hi ,

Am new to C++, i just need a sample script for replaceing a string, that scripts accepts two arguments serach string(STR1) and Replace string(ST2)
then replace STR1 with STR2.

Thanks in advance
$ echo "This is a string" | sed 's/a/the/'
This is the string
$
In Perl,

$ echo "This is a string" | perl -ne 'print if s/a/the/;'

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <string>
#include <iostream>
using namespace std;

string& find_replace(string& str,string& find,string& r){
	int x=0;
	int size=find.size();
	while(x<str.size()){
		x=str.find(find,x);
		str.replace(x,size,r);
		x+=size;}
	return str;}

int main(){
	string str="This is super string";
	string find="string";
	string r="man";
	find_replace(str,find,r);
	cout<<str;}

Untested, but I think it works =P

EDIT: Tested it, fixed the namespace, and the referencing issue
Last edited on
All programming languages are created for a purpose. Filename pattern search, directories traversing, simple maths etc are easily done using scripting languages.

Unless there is a compelling reason to use a compiled language, I tend to go for the scripting language approach. At least for regular expression crafting, I uses Perl extensively.
1
2
3
4
5
6
7
8
9
10
import java.io.*;

class Test {
  public static void main(String[] args) {
    String str="This is super string";
    String find="string";
    String r="man";
    System.out.println(str.replaceFirst(find,r));
  }
}


Anyone want to write one in pure C ? :P
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <stdio.h>
#include <string.h>

int main() {

  char *str="This is super string";
  char *find="string";
  char *r="man";

  char *found = strstr(str, find);
  if (found) {
    /*char dest[1024];*/
   char *dest = malloc(sizeof(char) * (
   found-str+strlen(r)+str+strlen(str)-(found+strlen(find))+1
   ));

    int i=0;
    char *ptr = str;
    while (ptr != found) {
      dest[i++] = *ptr++;
    }
    int j=0;
    for(j=0; j<strlen(r); j++) dest[i++] = r[j];
    ptr += strlen(find);
    while(*ptr!='\0') {
      dest[i++] = *ptr++;
    }
    dest[i] = '\0';
    printf("%s\n",dest);
    free(dest);
  }
  return 0;
}


Above in C code. Note this is un-safe code. dest[1024] can get buffer over-run problem.

Anyone know how we can figure out the total length so I can make dest as char *dest = new char[<computed length>] instead of current char dest[1024] ?

Edit: ok fix the computed length.... hope I get my maths correct else Segmentation fault!!!! C programmers should really use scripting languages to do search and replace or at least go for C++ string or Java String classes :O
Last edited on
Topic archived. No new replies allowed.