Wednesday, June 5, 2019

string operations


1. split the string based on the delimiter

Ref: https://www.codingame.com/playgrounds/14213/how-to-play-with-strings-in-c/string-split

2. reverse a words in a string and not a character:

way1:
https://www.geeksforgeeks.org/print-words-string-reverse-order/

way2:


SELVATHA-M-V0HE:test selvatha$ more string.c
#include <stdio.h>
#include <string.h>

int main()
{
        char str[] = "strtok needs to be called several times to split a string";
        int init_size = strlen(str);
        char delim[] = " ";
        char *array[20];
        int i=0,size;

        char *ptr = strtok(str, delim);
        array[i]=ptr;

        while(ptr != NULL)
        {
                i++;
                printf("'%s'\n", ptr);
                ptr = strtok(NULL, delim);
                array[i]=ptr;
        }
        size=i;

        printf("printing the char array\n");
        /* This loop will show that there are zeroes in the str after tokenizing */
        for (i = 0; i < size; i++)
        {
                printf("'%s'\n", array[i]);
        }
        printf("\n");

        return 0;
}
SELVATHA-M-V0HE:test selvatha$ gcc string.c 
SELVATHA-M-V0HE:test selvatha$ ./a.out
'strtok'
'needs'
'to'
'be'
'called'
'several'
'times'
'to'
'split'
'a'
'string'
printing the char array
'strtok'
'needs'
'to'
'be'
'called'
'several'
'times'
'to'
'split'
'a'
'string'

Ref: https://www.codingame.com/playgrounds/14213/how-to-play-with-strings-in-c/string-split

No comments:

Post a Comment