Get a Substring in C

Last Updated : 11 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Given a string str and pos and len that defines the starting and the length of the subarray. The task is to generate a substring of size len starting from the index pos

A substring is a contiguous sequence of characters within a String.

Examples:

Input: Str =”the”, pos=1, len=2
Output:  “th”
Explanation: substrings will be: “”, “t”, “h”, “e”, “th”, “he”, “the”.

Input: Str =”geeks”, pos=3, length=3
Output: “eks” 
Explanation: substrings are: “”, ” g”, “e”, “e”, “k”, “s”, “ge”, “ee”, “ek”, “ks”, “gee”, “eek”, “eks”, “geek”, “eeks”, “geeks”.

Approach: The problem can be solved following the below idea:

Create a character array and put the characters starting from pos to the character array to generate the substring. 

Follow the below steps to implement the idea:

  • Create a character array to store the substring.
  • Iterate from the given position for the given length to generate the substring required.
    • Then store each character in the character array and print the substring.

Follow the below illustration for a better understanding.

Illustration: 

Consider a string str=”abcde” , pos = 2, len = 3.

=> At i = 2 our ans = “c”

=> At i = 3, the character is ‘d’.
So add ‘d’ to the answer. 
Our ans = “cd”

=> At i = 4, the character is ‘e’.
So add ‘e’ to the answer.
Uur ans = “cde”.

Below is the implementation of the above approach.

C
// C implementation of code
#include <stdio.h>
#include <string.h>

// Function to get substr in C
void getString(int pos, int len, int i, char string[])
{

    char substring[1000];

    while (i < len) {
        substring[i] = string[pos + i - 1];
        i++;
    }

    substring[i] = '\0';

    // Print the result
    printf(substring);
    printf("\n");
    return 0;
}

// Driver code
int main()
{

    int pos, len, i = 0;

    // Testcase1
    char string[14] = "geeksforgeeks";

    // Initialize pos, len i.e., starting
    // index and len upto which we have to
    // get substring respectively.
    pos = 6;
    len = 5;
    printf("String: %s ", string);
    printf("\nsubstring is: ");

    // Function call
    getString(pos, len, i, string);

    // Testcase2
    char string2[5] = "abcde";
    pos = 1;
    len = 3;
    i = 0;
    printf("\nString: %s ", string2);
    printf("\nsubstring is: ");

    // Function call
    getString(pos, len, i, string2);

    return 0;
}

Output
String: geeksforgeeks 
substring is: forge

String: abcde 
substring is: abc

Time complexity: O(len)
Auxiliary space: O(len)

Using strncpy() function in C

We can also use strncpy() function in C to copy the substring from a given input string. It takes 3 parameters which are the destination string, source string along with starting index and length of the substring which we need to copy.

Syntax:

strncpy(destination_string,input_string+pos,len);

Here pos is the starting index and len is the length of the substring which we want to copy.

Below is the code for the above approach.

C
// C implementation of code
#include <stdio.h>
#include <string.h>

// Driver code
int main()
{
    int pos, len;

    // Testcase1
    char string[14] = "geeksforgeeks";
    char substring[14];

    // Initialize pos, len i.e., starting
    // index and len upto which we have to
    // get substring respectively.
    pos = 6;
    len = 5;
    printf("String: %s ", string);
    printf("\nsubstring is: ");

    // Using strncpy function to 
    // copy the substring
    strncpy(substring,string+(pos-1),len);
    printf(substring);

    // Testcase2
    char string2[5] = "abcde";
    char substring2[5];
    
    pos = 1;
    len = 3;
    printf("\nString: %s ", string2);
    printf("\nsubstring is: ");

    // Using strncpy function to 
    // copy the substring
    strncpy(substring2,string2+(pos-1),len);
    printf(substring2);
    return 0;
}

// This code is contributed by Pushpesh Raj.

Output
String: geeksforgeeks 
substring is: forge
String: abcde 
substring is: abc

Time complexity: O(len)
Auxiliary space: O(len)



Similar Reads

Partition given string in such manner that i'th substring is sum of (i-1)'th and (i-2)'th substring
Partition given string in such manner that i'th substring is sum of (i-1)'th and (i-2)'nd substring. Examples: Input : "11235813" Output : ["1", "1", "2", "3", "5", "8", "13"] Input : "1111223" Output : ["1", "11", "12", "23"] Input : "1111213" Output : ["11", "1", "12", "13"] Input : "11121114" Output : []Iterate through the given string by pickin
9 min read
Length of the largest substring which have character with frequency greater than or equal to half of the substring
Given a string S consisting of characters from 'a' to 'z'. The task is to find the length of the largest substring of S which contains a character whose frequency in the sub-string is greater than or equal to half of the length of the substring.Note: For odd-length substring, to calculate half-length consider integer division. For example, half of
10 min read
Minimum length of substring whose rotation generates a palindromic substring
Given a string str, the task is to find the minimum length of substring required to rotate that generates a palindromic substring from the given string. Examples: Input: str = "abcbd" Output: 0 Explanation: No palindromic substring can be generated. There is no repeated character in the string. Input: str = "abcdeba" Output: 3 Explanation: Rotate s
7 min read
Check if substring S1 appear after any occurrence of substring S2 in given sentence
Given strings S1, S2 and S, the task is to check if every substring of S which is same as S1 has another substring of S same as S2 before it. It is given that S1 is always present as a substring in the string S. Examples: Input: S1 = "code", S2 = "geek", S = "sxygeeksgcodetecode"Output: TrueExplanation: Substring S2 is present before both the occur
4 min read
Check if a string can be split into two substrings such that one substring is a substring of the other
Given a string S of length N, the task is to check if a string can be split into two substrings, say A and B such that B is a substring of A. If not possible, print No. Otherwise, print Yes. Examples : Input: S = "abcdab"Output: YesExplanation: Considering the two splits to be A="abcd" and B="ab", B is a substring of A. Input: S = "abcd"Output: No
5 min read
Count occurrences of substring X before every occurrence of substring Y in a given string
Given three strings S, X, and Y consisting of N, A, and B characters respectively, the task is to find the number of occurrences of the substring X before every occurrence of the substring Y in the given string S. Examples: Input S = ”abcdefdefabc”, X = ”def”, Y = ”abc”Output: 0 2Explanation:First occurrence of Y(= "abc"): No of occurrences of X(=
6 min read
Minimize replacement of bits to make the count of 01 substring equal to 10 substring
Given a binary string str. The task is to minimize the number of replacements of '0' by '1' or '1' by '0' to balance the binary string. A binary string is said to be balanced: "if the number of "01" substring = number of "10" substring". Examples: Input: str = "101010" Output: 1Explanation: "01" = 2 &amp; "10" = 3. So change the last character to '
4 min read
Longest substring whose any non-empty substring not prefix or suffix of given String
Given a string S of length N, the task is to find the length of the longest substring X of the string S such that: No non-empty substring of X is a prefix of S.No non-empty substring of X is a suffix of S.If no such string is possible, print −1. Examples: Input: S = "abcdefb"Output: 4Explanation: cdef is the substring satisfying the conditions. Inp
5 min read
Longest Substring of A that can be changed to Substring of B in at most T cost
Given two strings A and B of the same length and two positive integers K and T. The task is to find the longest substring of A that can be converted to the same substring at the same position in B in less than or equal to T cost. Converting any character of A to any other character costs K units. Note: If multiple valid substrings are possible then
13 min read
Minimum removals to make a string concatenation of a substring of 0s followed by a substring of 1s
Given binary string str of length N​​​​, the task is to find the minimum number of characters required to be deleted from the given binary string to make a substring of 0s followed by a substring of 1s. Examples: Input: str = "00101101"Output: 2Explanation: Removing str[2] and str[6] or removing str[3] and str[6] modifies the given binary string to
11 min read
three90RightbarBannerImg