A function

I need some help i am trying to do a interpreter for a auto/macro language. Whatever. I am trying to do aliases and what i would need is a function that has two parameters.
Something like this
1
2
3
4
5
6
7
8
9
10
11
12
13
  char replacestr(char inwhat[255],char what[255],char withwhat[255])
{
///Code goes here

}
int main()
{
char a[255];
strcpy(a,"this is a stirng");
replacestr(a,"stirng","string");
cout<<a<<endl;
return 0;
}

And here would be the output!
 
<output>: this is a string

Thank you for reading this!

Last edited on
Bump?
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
34
35
36
37
38
39
40
41
#include <string>
#include <cstring>

See: https://cal-linux.com/tutorials/strings.html
bool replace( std::string& inwhat, const std::string& what, const std::string& withwhat )
{
    const auto pos = inwhat.find(what) ;
    if( pos == std::string::npos ) return false ;
    inwhat.replace( pos, what.size(), withwhat ) ;
    return true ;
}

std::size_t replace_all( std::string& inwhat, const std::string& what, const std::string& withwhat )
{
    std::size_t cnt = 0 ;

    if( !what.empty() )
    {
        for( auto pos = inwhat.find(what) ; pos != std::string::npos ; ++cnt)
        {
            inwhat.replace( pos, what.size(), withwhat ) ;
            pos = inwhat.find( what, pos + withwhat.size() ) ;
        }
    }

    return cnt ;
}

// invariant: arguments are not null, inwhat is large enough to hold the replacement
void replace( char* inwhat, const char* what, const char* withwhat )
{
    std::string str = inwhat ;
    if( replace( str, what, withwhat ) ) std::strcpy( inwhat, str.c_str() ) ;
}

// invariant: arguments are not null, inwhat is large enough to hold the replacement
void replace_all( char* inwhat, const char* what, const char* withwhat )
{
    std::string str = inwhat ;
    if( replace_all( str, what, withwhat ) ) std::strcpy( inwhat, str.c_str() ) ;
}

http://coliru.stacked-crooked.com/a/1c6b90220771da59

For something more sophisticated (eg. replace only whole words, replace patterns in text), see std::regex::replace
http://en.cppreference.com/w/cpp/regex/regex_replace
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>
//#include <algorithm> //edit: not required 

int main()
{
    std::string s = "this is a stirng";

    s.replace(s.find("stirng"), std::string("stirng").length(), "string");

    std::cout << s;
}
Last edited on
Topic archived. No new replies allowed.