Thread: Finding and replacing a string in a given string using strtok

  1. #1
    Registered User
    Join Date
    Jan 2012
    Posts
    19

    Finding and replacing a string in a given string using strtok

    This is the snippet of my code that is supposed to find a certain string which is argv[1] within a given string (strings) and once found, replace that string with another string argv[2]. I designed it in a way that argv[1] and argv[2] can be of different lengths. The code first cuts up the given line into words and analyzes each word of the sentence. If this word/string is not the same as the string being searched for (argv[1]) , then the word will just be appended to a buffer (newstrings) and then later on written to a file.

    For some reason, the program doesn't work. Help please

    Code:
            /*Some code*/
        while(fgets(strings,1000,f1)!=NULL)
        {
            if(strstr(strings,argv[1])!=NULL) 
            {
                token=strtok(strings," ");
                while(strtok(NULL," ")!=NULL);
                    {
                        if(*token==*argv[1])
                        {
                            strcat(newstrings,argv[2]);
                            strcat(newstrings," ");
                        }
                        else
                        {
                            strcat(newstrings,token);
                            strcat(newstrings," ");
                        }
                        token=strtok(NULL," ");            
                    }
            }
            else
            {
                strcpy(newstrings,strings);
    
    
            }
            fputs(newstrings,f2);
        }

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    You need to use strcmp(), you can't compare strings directly, in C:

    NO good!
    string1 == string2

    Good!
    if((strcmp(string1, string2)) ==0)

    In the above, if string1 is > string2, then strcmp() will return a value less than 0, if string2 is >, then strcmp() will return a value > 0.

  3. #3
    Registered User
    Join Date
    Jan 2012
    Posts
    19
    Okay I corrected that part but it still doesn't work properly Maybe posting my whole code might help:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    
    
    int main(int args, char *argv[4])
    {
        FILE *f1;
        FILE *f2;
        char *strings=0;
        char *newstrings=0;
        char *token=NULL;    
        strings=(char *)malloc(1000);
        newstrings=(char *)malloc(1000);
        
        if((strings==NULL)||(newstrings==NULL))
        {
            printf("Memory allocation was not successfull.");
            system("pause");
            return 0;
        }
        
        if(args<4)
        {
            puts("Error: Not enough input parameters");
            puts("Usage: ./change <oldword> <newword> <infile> <newfile>");
            system("pause");
            return 0;
            
        }
        
        f1=fopen(argv[3],"r");
        f2=fopen(argv[4],"w");
        if(f1==NULL)
        {
            puts("No such file exists");
            system("pause");
            return 0;
        }
        while(fgets(strings,1000,f1)!=NULL)
        {
            if(strstr(strings,argv[1])!=NULL) 
            {
                token=strtok(strings," ");
                while(strtok(NULL," ")!=NULL);
                    {
                        if(strcmp(token,argv[1])==0)
                        {
                            strcat(newstrings,argv[2]);
                            strcat(newstrings," ");
                        }
                        else
                        {
                            strcat(newstrings,token);
                            strcat(newstrings," ");
                        }
                        token=strtok(NULL," ");            
                    }
            }
            else
            {
                strcpy(newstrings,strings);
    
    
            }
            fputs(newstrings,f2);
        }    
        free(strings);
        free(newstrings);
        printf("New file <%s> generated!\n",argv[4]);
        
        
        fclose(f1);
        fclose(f2);
        system("pause");
        return 0;
    }

  4. #4
    Registered User
    Join Date
    Jan 2012
    Posts
    19
    But im pretty sure that the problem lies in the snippet of code that was posted at the start of this thread. The program uses command line arguments.

  5. #5
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    I'm quite sure that you can:

    1) check for any warnings or errors from the compiler and fix them or post them up.
    2) add some print lines of code, with a getchar() after it, so you can see what the status is of the strings and substrings.

    What is the content of those strings, within the while loop? There's an error, of course, but it's one that you need to see the string values, to find easily. At least, for me and you.

    We get this all the time, btw. Humans have an aversion to adding a print line of code, with a getchar() after it - don't ask me why. They'll argue this and that for hours, rather than using the debug line of code mentioned above, to fix the problem, in 10 minutes.

    Be sure to print out what your *argv strings actually are, as well. There's no need to solve string problem blindly, when the computer will be glad to print out the string contents for you.

  6. #6
    Registered User
    Join Date
    Jan 2012
    Posts
    19
    Okay so nothing worked. I've tried cutting up the string into words, cutting them up into tokens then analyzing them. NOTHING WORKS :| So I started over and I'm back at trying to figure out a way to find a word within a string(sentence) and replace it with another word. The words don't have to be the same length. Any suggestions?

  7. #7
    Registered User
    Join Date
    Dec 2011
    Posts
    795
    Let's say the user didn't enter the right amount of arguments:
    Code:
        strings=(char *)malloc(1000);
        newstrings=(char *)malloc(1000);
         
        if((strings==NULL)||(newstrings==NULL))
        {
            printf("Memory allocation was not successfull.");
            system("pause");
            return 0;
        }
         
        if(args<4)
        {
            puts("Error: Not enough input parameters");
            puts("Usage: ./change <oldword> <newword> <infile> <newfile>");
            system("pause");
            return 0;
             
        }
    Congratulations, you wasted 2000 bytes of memory. You should fix this by allocating AFTER you check to make sure the right amount of args are used.

    Get rid of system("pause")

    The most important thing (and probably why it doesn't work), you have an extra semicolon:
    Code:
    while(strtok(NULL," ")!=NULL);
    This prevents the while loop from doing what's inside the loop.

  8. #8
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by haroldco View Post
    Okay so nothing worked. I've tried cutting up the string into words, cutting them up into tokens then analyzing them. NOTHING WORKS :| So I started over and I'm back at trying to figure out a way to find a word within a string(sentence) and replace it with another word. The words don't have to be the same length. Any suggestions?
    You tried "everything" -- EXCEPT putting a print line of code and a getchar(), inside the while loop.

    Because if you did, you would have seen that nothing from there, was being printed out.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simple Removal of string in string via strtok.
    By Vincent Wouters in forum C Programming
    Replies: 6
    Last Post: 11-11-2011, 01:48 PM
  2. Replacing a string in a string with another string
    By Dontgiveup in forum C++ Programming
    Replies: 3
    Last Post: 04-24-2011, 07:43 PM
  3. Replies: 3
    Last Post: 10-14-2008, 05:56 PM
  4. Replacing and finding chars in a string
    By xshapirox in forum C++ Programming
    Replies: 5
    Last Post: 10-11-2004, 11:40 PM
  5. Replacing string in file
    By Spedge in forum C Programming
    Replies: 1
    Last Post: 08-19-2003, 02:53 AM