1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Strings in C

  1. Jan 18, 2009 #1
    1. The problem statement, all variables and given/known data

    Ok, i need to make a program that will search for a substring in a given string, and replace it with another one.

    3. The attempt at a solution

    Code (Text):

    using namespace std;

    int fsubstitute(char *ulazni, char *prvi, char *drugi);

    int main()
        char initial[255];
        char find[255];
        char replace[255];



    int fsubstitute(char *initial, char *find, char *replace)
        char *temp1;
        int i,j,k,c,l,n;
        i = j = k = c = l = n = 0;
        n = strlen(find);
        l = strlen(initial);
        char temp2[200];
            if(strstr(initial,find)!= NULL)
            temp1 = strstr(initial,find)+ n;
            temp2[i] = *(initial+i);
            temp2[i] = '\0';
            initial = temp2;
            initial = strcat(initial,replace);
            initial = strcat(initial,temp1);
        }while(strstr(initial,find)!= NULL);
        cout << initial << endl;
        return 0;
    I used cout since it is easier to write, and that's why i included a c++ library/

    Can you tell me what's wrong with my code?
  2. jcsd
  3. Jan 18, 2009 #2

    D H

    Staff: Mentor

    Does it compile? If not, what is the message?

    If it does compile, does it compile clean with all warnings enabled?

    Have you used a debugger? If so, where did your code behave other than you expected?

    If you haven't used a debugger, why not?
  4. Jan 18, 2009 #3
    I mean everything's fine with the syntax, it just won't do its job.
  5. Jan 18, 2009 #4

    D H

    Staff: Mentor

    So, have you debugged your program? Do you even know what that means?

    We treat computer programming problems here the same as physics homework problems: You have to show your work. In the case of a computer program, showing your work means you telling us a bit about the execution of your program. We don't do physics homework for students because that is a disservice. The same goes for us debugging your program for you.
  6. Jan 18, 2009 #5
    I solved it, thanks for the help anyway.
  7. Jan 18, 2009 #6

    D H

    Staff: Mentor

    Does your program work for nasty cases, for example initial="this is a test", find="is", replace="this"?
  8. Jan 18, 2009 #7
    Yes it does :)
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?

Similar Discussions: Strings in C
  1. C++ strings help (Replies: 2)

  2. Help with C++ strings (Replies: 3)