Open In App

Print substring of a given string without using any string function and loop in C

Improve
Improve
Like Article
Like
Save
Share
Report

Write a function mysubstr() in C that doesn’t use any string function, doesn’t use any loop, and prints substring of a string. The function should not modify contents of string and should not use a temporary char array or string. For example mysubstr(“geeksforgeeks”, 1, 3) should print “eek” i.e., the substring between indexes 1 and 3.

One solution is to use recursion. Thanks to Gopi and oggy for suggesting this solution. 

C




#include<stdio.h>
 
// This function prints substring of str[] between low and
// high indexes (both inclusive).
void mysubstr(char str[], int low, int high)
{
    if (low<=high)
    {
        printf("%c", str[low]);
        mysubstr(str, low+1, high);
    }
}
 
int main ()
{
    char str[] = "geeksforgeeks";
    mysubstr(str, 1, 3);
    return 0;
}


Output

eek

Time Complexity: O(N), where N is the length of the string
Auxiliary Space: O(1)

How to do it if recursions is also not allowed? We can always use pointer arithmetic to change the beginning part. For example (str + i) gives us address of i’th character. To limit the ending, we can use width specifier in printf which can be passed as an argument when * is used in format string. 

C




#include <stdio.h>
 
// This function prints substring of str[] between low and
// high indexes (both inclusive).
void mysubstr(char str[], int low, int high)
{
    printf("%.*s", high - low + 1, (str + low));
}
 
int main()
{
    char str[] = "geeksforgeeks";
    mysubstr(str, 1, 3);
    return 0;
}


Output

eek

Time Complexity: O(N), where N is the length of the string
Auxiliary Space: O(1)



Last Updated : 28 Dec, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads