Find Substring of a Given String

Description

A substring is a part of a string.

C/C++

/* C program to find substring of specified length */
//Save it as ExtractSubstring.c

#include<stdio.h>
int main(){

    char str[100], substr[100];
    int pos, len, i, j=0;

    printf("Enter a string : ");
    gets(str);

    printf("Enter the position where to extract substring : ");
    scanf("%d",&pos);

    printf("Enter the length of substring : ");
    scanf("%d",&len);
    
    
    //Assigning the start position to a variable
    
    i=pos;

    
    //Check until loop ends or find substring of required length
    
    while(str[i]!='\0' && len>0){

       substr[j] = str[i];
       i++;
       j++;
       len--;
    }

    
    //Assigning null to end striing
    
    substr[j] = '\0';

    printf("The substring is : %s",substr);

    return 0;
}
Input:
Enter a string : Hello World!
Enter the position where to extract substring : 2
Enter the length of substring : 5

Output:
The substring is : llo W

Java

/* Java program to find substring of specified length */
//Save it as ExtractSubstring.java


import java.io.*;
import java.util.Scanner;

public class ExtractSubstring {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        
        System.out.println("Enter a string : ");
        String str = scanner.nextLine();
        
        System.out.println("Enter start Index : ");
        int start = scanner.nextInt();
        
        System.out.println("Enter end Index : ");
        int end = scanner.nextInt();
        
        
        //There are two method to find substring of a string
        /*In case of substring starting index is inclusive 
          and ending index is exclusive*/
        
        
        /*public String substring(int start) : 
                 print all substring starting from specified Index start*/
        
        
        System.out.println("The substring : "+str.substring(start));
        
        
        /* public String substring(int startIndex, int endIndex): 
                  print all substring from Index start and end */
        
        System.out.println("The substring : "+ str.substring(start, end));
        
    }
}
Input:
Enter a string : 
Hello World!
Enter start Index : 
2
Enter end Index : 
7

Output:
The substring : llo World!
The substring : llo W

Related Programs

1) How to find Length or Size of a String
2) Program to check String is Palindrome
3) Program to sort characters of strings in alphabetical order
4) Program to remove vowels from a String
5) Program to Multiply Numbers Present in a String
6) Program to remove given number from a string
7) Program to count Vowels, Consonants, Digits and Whitespaces
8) Program to Add numbers present in a String
9) Find Occurrence Of Each Word In a Sentence
10) Print All Unique Words Of A String
11) Program To Print Unique Word Of A String Using Set
Share Me

Leave a Reply