Home > Mobile >  How to change the position of words in sentence by using recursion in C?
How to change the position of words in sentence by using recursion in C?

Time:12-18

How to make ABC DEF GHI to GHI DEF ABC by using recursive function?

void reverse(char *str)
{
    if (*str)
    {
        if(str != ' ')
        {
            str  = 1;
        }
        reverse(str 1);
        printf("%c", str);
    }
}

CodePudding user response:

The printf specifier %s can be used with a precision of *, which allows you to pass an integer value (as an int) specifying the maximum number of bytes to read from the string.

strspn and strcspn can be used to find spans in strings, consisting of characters found or not found in their second argument, respectively.

Used together, these functions allow us to skip over leading whitespace, and find the length of each substring delimited by whitespace.

#include <stdio.h>
#include <string.h>

void print_sentence_backwards(const char *sent)
{
    sent  = strspn(sent, " ");    
    
    if (*sent) {
        size_t n = strcspn(sent, " "); 
        print_sentence_backwards(sent   n);
        printf("%.*s ", (int) n, sent);
    }
}

int main(void)
{
    print_sentence_backwards("ABC DEF GHI");
    putchar('\n');
}
GHI DEF ABC 
  • Related