简体   繁体   中英

split string by semicolon without strtok

I am using C for this. I have been trying to split the string using semi colon as a delimiter. Using command line argument I will pass a string such as, "1 + 2; 3 + 4" I want to get out put as 1 + 2 3 + 4 I cannot use strtok for this.

I have tried to run a for loop through the string but it is not working.

 for (int i = 0; argv[1][i] != ';';i++)
    {
        char* argv;
        printf("\n%s", *(argv[1][]));
    }

THIS IS EDITED PART

for (int i = 0; argv[1][i] != ';' || argv[1][i] != '\0'; i++)
    {
        for (int j = 0; argv[1][j]; j++)
        {
            char string = argv[1][i] - argv[1][j];

            printf("\n%s", string);
        }

    }

WHEN I TRY TO RUN THIS HAPPEN

./check "1 + 2; 3 + 4"
number of arguments: 2
1 + 2; 3 + 4
(null)

why i am getting null here?

I think you want something like:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(int argc, char **argv)
{
        char *str, *start;
        str = malloc( argc > 1 ? strlen(argv[1]) : 50 );
        strcpy( str, argc > 1 ? argv[1] : "1 + 2; 3+4" );
        /* Error checking omitted for brevity */
        do {
                for( start = str; *str && *str != ';'; str++ )
                        ;
                if(*str == ';')
                        *str++ = '\0';
                printf("%s\n", start);
        } while( *str );
}

Given your stated preference to avoid any functions from the standard library that are declared in string.h, perhaps you prefer:

#include <stdio.h>
#include <stdlib.h>

size_t len( const char *c ) {
        size_t s = 0;
        while( *c++ )
                s+=1;
        return s;
}
int
main(int argc, char **argv)
{
        char *str, *start;
        const char *target = argc > 1 ? argv[1] : "1 + 2; 3 + 4";
        start = str = malloc( len(target) + 1);
        /* Error checking omitted for brevity */
        while( (*str++ = *target++) != '\0')
                ;
        str = start;
        do {
                for( start = str; *str && *str != ';'; str++ )
                        ;
                if(*str == ';')
                        *str++ = '\0';
                printf("token: %s\n", start);
        } while( *str );
        return 0;
}

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