Skip to main content

StringBuffer substring() method in Java with Examples

In StringBuffer class, there are two types of substring method depending upon the parameters passed to it.

substring(int start)

The substring(int start) method of StringBuffer class is the inbuilt method used to return a substring start from index start and extends to end of this sequence. The string returned by this method contains all character from index start to end of the old sequence.

Syntax:

public String substring(int start)

Parameters: This method accepts only one parameter start which is Integer type value refers to the start index of substring.

Return Value: This method returns the substring lie in the range start to end of old sequence.

Exception: This method throws StringIndexOutOfBoundsException if start is less than zero, or greater than the length of this object.

Below programs illustrate the StringBuffer substring() method:

Example 1:




// Java program to demonstrate
// the substring() Method.
  
class GFG
    public static void main(String[] args)
    
  
        // create a StringBuffer object
        // with a String pass as parameter
        StringBuffer str
            = new StringBuffer("GeeksForGeeks");
  
        // print string
        System.out.println("String contains = "
                           + str);
  
        // get substring start from index 5
        // using substring() and print results
        System.out.println("SubSequence = "
                           + str.substring(5));
    

Output:
String contains = GeeksForGeeks
SubSequence = ForGeeks

Example 2: To demonstrate StringIndexOutOfBoundsException




// Java program to demonstrate
// Exception thrown by the substring() Method.
  
class GFG
    public static void main(String[] args)
    
  
        // create a StringBuffer object
        // with a String pass as parameter
        StringBuffer str
            = new StringBuffer("Indian Team Played Well");
  
        try
            // get substring starts from index -7
            // using substring() and print
            str.substring(-7);
        
  
        catch (Exception e)
            System.out.println("Exception: " + e);
        
    

Output:
Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: -7

substring(int start, int end)

The substring(int start, int end) method of StringBuffer class is the inbuilt method used to return a substring start from index start and extends to the index end-1 of this sequence. The string returned by this method contains all character from index start to index end-1 of the old sequence.

Syntax:

public String substring(int start)

Parameters: This method accepts two parameter start which is Integer type value refers to the start index of substring and end which is also a Integer type value refers to the end index of substring.

Return Value: This method returns the substring lie in the range index start to index end-1 of old sequence.

Exception: This method throws StringIndexOutOfBoundsException if start or end are negative or greater than length(), or start is greater than end.

Below programs illustrate the StringBuffer.substring() method:

Example 1:




// Java program to demonstrate
// the substring() Method.
  
class GFG
    public static void main(String[] args)
    
  
        // create a StringBuffer object
        // with a String pass as parameter
        StringBuffer str
            = new StringBuffer("GeeksForGeeks");
  
        // print string
        System.out.println("String contains = " + str);
  
        // get substring start from index 5 to index 8
        // using substring() and print results
        System.out.println("SubSequence = "
                           + str.substring(5, 8));
    

Output:
String contains = GeeksForGeeks
SubSequence = For

Example 2: To demonstrate StringIndexOutOfBoundsException




// Java program to demonstrate
// Exception thrown by the substring() Method.
  
class GFG
    public static void main(String[] args)
    
  
        // create a StringBuffer object
        // with a String pass as parameter
        StringBuffer str
            = new StringBuffer("Indian Team Played Well");
  
        try
            // get substring starts from index 7
            // and end at index 3
            // using substring() and print
            str.substring(9, 3);
        
  
        catch (Exception e)
  
            System.out.println("Exception: " + e);
        
    

Output:
Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: -6

References:

https://neveropen.tech/stringbuffer-substring-method-in-java-with-examples/?feed_id=76&_unique_id=683ce69e10f20

Comments

Popular posts from this blog

Bare Metal Billing Client Portal Guide

Contents Order a Bare Metal Server My Custom / Contract Pricing View Contract Details Location Management Order History & Status View Order Details Introduction The phoenixNAP Client Portal allows you to purchase bare metal servers and other phoenixNAP products and services. Using the intuitive interface and its essential tools, you can also easily manage your infrastructure. This quick guide will show you how to use the new form to order a bare metal server and how to navigate through new bare metal features within the phoenixNAP Client Portal. Order a Bare Metal Server An order form is an accordion-based process for purchasing phoenixNAP products. Our order form allows you to view the pricing and order multiple products from the same category at the same time. Note: The prices on the form are per month . A contract is not required. However, if you want a contracted price, you may be eligible for a discount depending on the quantity and ...

Add an element in Array to make the bitwise XOR as K

Given an array arr[] containing N positive integers, the task is to add an integer such that the bitwise Xor of the new array becomes K. Examples: Input: arr[] = 1, 4, 5, 6, K = 4 Output: 2 Explanation: Bit-wise XOR of the array is 6.  And bit-wise XOR of 6 and 2 is 4. Input: arr[] = 2, 7, 9, 1, K = 5 Output: 8   Approach: The solution to the problem is based on the following idea of bitwise Xor: If for two numbers X and Y , the bitwise Xor of X and Y is Z then the bitwise Xor of X and Z is Y. Follow the steps to solve the problem: Let the bitwise XOR of the array elements be X .  Say the required value to be added is Y such that X Xor Y = K . From the above observation, it is clear that the value to be added (Y) is the same as X Xor K . Below is the implementation of the above approach: C++ // C++ code to implement the above approach   #include using namespace std;   // Function to find the required value int find_...

Mahotas – Template Matching

In this article we will see how we can do template matching in mahotas. Template is basically a part or structure of image. In this tutorial we will use “lena” image, below is the command to load it.   mahotas.demos.load('lena') Below is the lena image      In order to do this we will use mahotas.template_match method Syntax : mahotas.template_match(img, template) Argument : It takes image object and template as argument Return : It returns image object    Note : Input image should be filtered or should be loaded as grey In order to filter the image we will take the image object which is numpy.ndarray and filter it with the help of indexing, below is the command to do this   image = image[:, :, 0] Below is the implementation    Python3 # importing required libraries import mahotas import mahotas.demos from pylab import gray, imshow, show import numpy as np import matplotlib.pyplot as plt      # loading image ...