简体   繁体   中英

Seperating all characters in a string before a strstr pointer in C

I am building a find and replace program in C. it needs to be able to replace whatever is searched for in a text file with some thing else.
Eg. Search elo in input.txt replace with ELO
Result: developers devELOpers
eg search el replace EL hello hELlo welcome wELcome

I am having real trouble getting all the characters in a string before a pointer. I can get the single words and the pointer for the search word and i can get everything after the search term but i cannot get everything before the searched characters. Tried strlen on the whole word and subtracting to no avail. I also can get the length of the first part of the word i need. Thanks for any help.

search for era in operating:

Outputs are

firstMatch= erating

End part =ting

startLength 2

    #include <stdio.h>
#include<stdlib.h>
#include <string.h> 
#define LINE_LENGTH 1000


//Function to remove a newline character and replace it with a null terminator.
void remove_newline(char *str) 
{
    int len =strlen (str);

    if (len>0 &&str[len -1] == '\n')
    str[len -1] = '0';
}


int main(int argc, char **argv)
{
    char* searchWord = argv[1]; //Define the string searched for as argument  1.
    char* replaceWord = ""; // Initialise the word for replacing search word.
    char* text_File= ""; // Initialise the text file


    for(int i = 0; i < argc; i++)
    {
        if (strcmp(argv[i],"-r")==0)
        {

            replaceWord = argv[i+1]; // Identify the replacemnt word as the argument that comes after "-r".
        }

        if (strcmp(argv[i],"-i")==0)
        {
            text_File = argv[i+1]; // Identify the file word as the argument that comes after "-i".
        }


    }   

    char slen= strlen(searchWord);

    printf("You have searched for %s\n", searchWord); // Clarify for the user their search terms and input file.
    printf("In the file %s\n", text_File);


    FILE *input_file = fopen(text_File, "r"); // Open the text file
    char line [LINE_LENGTH];

    FILE *write_file = fopen("output.txt", "w"); //Create a new file for writing to.



`       while (fgets(line, LINE_LENGTH, input_file) != NULL)      ***// Loop through the contents of the input file.***
    {


    char *currentWord;     ***// Separate the words at any of "\n ,.-".***
    char *tempWord; 

    currentWord = strtok(line, "\n ,.-");
    while (currentWord != NULL)     ***// Loop through every seperated word.***
    {
        remove_newline(currentWord); //Remove the newline character form the current word.
        if (strstr(currentWord, searchWord)!= NULL)      ***// Check if the current word contains the searh word***
        {
            printf ("%s ", currentWord);      ***// If it does print to console the word containing it***

            char currLength= strlen(currentWord);
            printf("%d\n", currLength);
            char* firstMatch= strstr(currentWord, searchWord);      ***// Find the first occurence of the searched term***
            printf ("firstMatch %s\n ", firstMatch);      ***//Print evrything after and including search.***
            char* lastPart = firstMatch + slen;      ***// Get the part after the search***
            printf ("End part %s\n ", lastPart); 
            char rest = strlen(firstMatch);


            char startLength = currLength - rest;  

This is where it doesn't work.

            char* startPart = firstMatch - startLength;
            printf ("start Part %s\n ", startPart);
            printf ("startLength %d\n\n ", startLength);`

The reason for the unexpected result when you try to print the "before the match" portion of the word is that there's nothing in the word string that will cause the

    printf("start Part %s\n ", startPart);

call to stop after it has printed the first startLength characters of the word. When printf is told to print a string, it prints all characters from the starting point until it encounters a \\0 terminator. Here, the only \\0 is at the end of the word, so printf prints the entire word.

If you want to only print the first few characters of the word, you have to either construct a \\0 -terminated string that only contains those first few characters or you have to print them by using a mechanism that does not try to treat them as a string.

To construct a \\0 -terminated start string you could temporarily overwrite the first character of the match with a \\0 , then call printf , and then restore the match character. Something like:

    char savedFirstMatch = *firstMatch;
    *firstMatch = '\0';
    printf("start Part %s\n ", startPart);
    *firstMatch = savedFirstMatch;

If you don't want to do that then you could use a for loop to print only the first startLength characters as individual characters, not as a string, preceded and followed by a printf or puts that emits whatever extra stuff you want to print around those characters. In this case the extra stuff is a "start Part " string before the characters, and a newline and space afterwards (assuming that that space isn't just a typo). That would look something like:

    puts("start Part ");
    unsigned startIndex;
    for (startIndex = 0; startIndex < startLength; ++startIndex) {
        putchar(startPart[startIndex]);
    }
    puts("\n ");

Of course if you aren't comfortable with puts and putchar you can use printf("%s", ...) and printf("%c", ...) instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM