How to extract a substring from a string in C?

后端 未结 5 1611
野的像风
野的像风 2020-12-11 04:15

I tried using strncmp but it only works if I give it a specific number of bytes I want to extract.

char line[256] = This \"is\" an example. //I want to extr         


        
5条回答
  •  隐瞒了意图╮
    2020-12-11 04:25

    Here is a long way to do this: Assuming string to be extracted will be in quotation marks (Fixed for error check suggested by kieth in comments below)

    #include 
    #include 
    #include 
    
    int main(){
    
        char input[100];
        char extract[100];
        int i=0,j=0,k=0,endFlag=0;
    
        printf("Input string: ");
        fgets(input,sizeof(input),stdin);
        input[strlen(input)-1] = '\0';
    
        for(i=0;i

    Output(1):

    $ ./test
    Input string: extract "this" from this string
    Extract = this
    

    Output(2):

    $ ./test
    Input string: Another example to extract "this gibberish" from this string
    Extract = this gibberish
    

    Output(3):(Error check suggested by Kieth)

    $ ./test

    Input string: are you "happy now Kieth ?
    1.Your code only had one quotation mark.
    2.So the code extracted everything after that quotation mark
    3.To make sure buffer overflow doesn't happen in this case:
    4.Modify the extract buffer size to be the same as input buffer size
    
    extracted string: happy now Kieth ?
    

    --------------------------------------------------------------------------------------------------------------------------------

    Although not asked for it -- The following code extracts multiple words from input string as long as they are in quotation marks:

    #include 
    #include 
    #include 
    
    int main(){
    
        char input[100];
        char extract[50];
        int i=0,j=0,k=0,endFlag=0;
    
        printf("Input string: ");
        fgets(input,sizeof(input),stdin);
        input[strlen(input)-1] = '\0';
    
        for(i=0;i

    Output:

    $ ./test
    Input string: extract "multiple" words "from" this "string"
    Extract = multiplefromstring
    

提交回复
热议问题