Showing posts with label StringBuilder Class. Show all posts
Showing posts with label StringBuilder Class. Show all posts

StringBuilder class Methods in Java Part -II

 java.lang.StringBuilder

A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.


Some methods of StringBuilder class


indexOf(String str, int fromIndex): It returns the index within this string of the first occurrence of the specified substring, starting at the specified index.


insert(int offset, Object obj): It inserts the string representation of the Object argument into this character sequence. 


insert(int index, char[] str, int offset, int len):  It inserts the string representation of a subarray of the array argument into this sequence. 


insert(int dstOffset, CharSequence s, int start, int end): It inserts a subsequence of the specified CharSequence into this sequence. 


lastIndexOf(String str): It returns the index within this string of the last occurrence of the specified substring.


lastIndexOf(String str, int fromIndex):  It returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.


length(): It returns the length (character count).


offsetByCodePoints(): It returns the index within this sequence that is offset from the given index by codePointOffset code points.


replace(): It replaces the characters in a substring of this sequence with characters in the specified String. 


reverse(): The character sequence to be replaced by the reverse of the sequence.


setCharAt(): The character at the specified index is set to ch.


setLength():  It sets the length of the character sequence.


subSequence(): It returns a new character sequence that is a subsequence of this sequence.


substring(int start): It returns a new String that contains a subsequence of characters currently contained in this character sequence.


substring(int start, int end): It returns a new String that contains a subsequence of characters currently contained in this sequence.


toString(): It returns a string containing the characters in this sequence in the same order as this sequence.


trimToSize(): It attempts to reduce the storage used for the character sequence.


Some more Methods of StringBuilder class


StringBuilder trimToSize() in Java

trimToSize(): This method is available in java.lang.AbstractStringBuilder class of Java.

Syntax:

void java.lang.AbstractStringBuilder.trimToSize()

This method attempts to reduce storage used for the character sequence. If the buffer is larger than necessary to hold its current sequence of characters, then it may be resized to become more space-efficient.

Parameters: NA

Exceptions: NA

Approach

Java

public class TrimToSize {
    public static void main(String[] args) {

        StringBuilder str = 
new StringBuilder("Java is a progamming language.");

        System.out.println("Capacity = " + 
str.capacity() + " Size = " + str.length());
        str.trimToSize();

        System.out.println("Capacity = " +
 str.capacity() + " Size = " + str.length());
    }
}


Output:

Capacity = 46 Size = 30 Capacity = 30 Size = 30


StringBuilder toString() in Java

toString(): This method is available in java.lang.StringBuilder class of Java.

Syntax:

String java.lang.StringBuilder.toString()

This method returns a string containing the characters in this sequence in the same order as this sequence.

Note: The length of the string will be the length of this sequence.

Parameters: NA

Returns: a string consisting of exactly this sequence of characters.

Exceptions: NA

For Example:

StringBuilder str = new StringBuilder("Hello World")

str.toString() = > It returns Hello World.

Approach

Java

public class ToString {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        System.out.println(str.toString());
    }
}

Output:

Hello World

StringBuilder substring() range in Java

substring(): This method is available in java.lang.AbstractStringBuilder class of Java.

Syntax:

String java.lang.AbstractStringBuilder.substring(int start, int end)

This method takes two arguments of type int as its parameters. This method returns a new String that contains a subsequence of characters currently contained in this sequence. The substring begins at the specified start and extends to the character at index end - 1 (or we can say it returns the substring in the range [start, end) ).

Parameters: Two parameters are required for this method.

start: The beginning index, inclusive.

end: The ending index, exclusive.

Returns: The new string.

Throws:

StringIndexOutOfBoundsException - if start or end is negative or greater than length(), or start is greater than the end.

For Example:

StringBuilder str = new StringBuilder("Hello World")

int start = 2, end = 7

str.substring(start,end) = > It returns llo W.

Approach 1: When both the values are in the range.

Java

public class SubstringRange {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        int start = 2, end = 7;
        System.out.println(str.substring(start, end));
    }
}

Output:

llo W


Approach 2: When any value is out of range.

Java

public class SubstringRange {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        int start = 2, end = 15;
        System.out.println(str.substring(start, end));
    }
}


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: start 2, end 15, length 11 at java.base/java.lang.AbstractStringBuilder.checkRangeSIOOBE(AbstractStringBuilder.java:1802) at java.base/java.lang.AbstractStringBuilder.substring(AbstractStringBuilder.java:1066) at java.base/java.lang.StringBuilder.substring(StringBuilder.java:85)


StringBuilder substring() in Java

substring(): This method is available in java.lang.AbstractStringBuilder class of Java.

Syntax:

String java.lang.AbstractStringBuilder.substring(int start)

This method takes one argument of type int as its parameter. This method returns a new String that contains a subsequence of characters currently contained in this character sequence. The substring begins at the specified index and extends to the end of this sequence.

Parameters: One parameter is required for this method.

start: The beginning index, inclusive.

Returns: The new string.

Throws:

StringIndexOutOfBoundsException - if start is less than zero, or greater than the length of this object.

For Example:

StringBuilder str = new StringBuilder("Hello World")

int start = 4

str.substring(start) = > It returns o World.

Approach 1: When the index is in the range.

Java

public class Substring {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        int start = 4;
        System.out.println(str.substring(start));
    }
}

Output:

o World


Approach 2: When the index is out of range.

Java

public class Substring {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        int start = 16;
        System.out.println(str.substring(start));
    }
}


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: start 16, end 11, length 11 at java.base/java.lang.AbstractStringBuilder.checkRangeSIOOBE(AbstractStringBuilder.java:1802) at java.base/java.lang.AbstractStringBuilder.substring(AbstractStringBuilder.java:1066) at java.base/java.lang.StringBuilder.substring(StringBuilder.java:85) at java.base/java.lang.AbstractStringBuilder.substring(AbstractStringBuilder.java:1017) at java.base/java.lang.StringBuilder.substring(StringBuilder.java:85)


StringBuilder subSequence() in Java

subSequence(): This method is available in java.lang.AbstractStringBuilder class o Java.

Syntax:

CharSequence java.lang.AbstractStringBuilder.subSequence(int start, int end)

This method takes two arguments of type int as its parameters. This method returns a new character sequence that is a subsequence of this sequence.

Parameters: Two parameters are required for this method.

start: the start index, inclusive.

end: the end index, exclusive.

Returns: the specified subsequence.

Throws:

StringIndexOutOfBoundsException - if start or end is negative,if end is greater than length(),or if start is greater than end.

For Example:

StringBuilder str = new StringBuilder("Hello World")

int start = 3, end = 8

str.subSequence(start,end) = > It returns lo Wo.

Approach 1: When the index is in the range.

Java

public class SubSequence {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        int start = 3, end = 8;
        System.out.println(str.subSequence(start, end));
    }
}

Output:

lo Wo


Approach 2: When the index is out of range.

Java

public class SubSequence {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        int start = 10, end = 8;
        System.out.println(str.subSequence(start, end));
    }
}


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: start 10, end 8, length 11 at java.base/java.lang.AbstractStringBuilder.checkRangeSIOOBE(AbstractStringBuilder.java:1802) at java.base/java.lang.AbstractStringBuilder.substring(AbstractStringBuilder.java:1066) at java.base/java.lang.StringBuilder.substring(StringBuilder.java:85) at java.base/java.lang.AbstractStringBuilder.subSequence(AbstractStringBuilder.java:1048) at java.base/java.lang.StringBuilder.subSequence(StringBuilder.java:85)


StringBuilder setLength() in Java

setLength(): This method is available in java.lang.AbstractStringBuilder class of Java.

Syntax:

void java.lang.AbstractStringBuilder.setLength(int newLength)

This method takes one argument of type int as its parameter. This method sets the length of the character sequence. The sequence is changed to a new character sequence whose length is specified by the argument.

Note:

1. If the newLength argument is less than the current length, the length is changed to the specified length.

2. The newLength argument must be greater than or equal to 0.

Parameters: One parameter is required for this method.

newLength: the new length.

Throws:

StringIndexOutOfBoundsException - if the newLength argument is negative.

Approach 1: When the newLength is greater than or equal to 0.

Java

public class SetLength {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello");

        int newLength = 100;
        str.setLength(newLength);

        System.out.println(str.length());
    }
}

Output:

100


Approach 2: When the newLength is negative.

Java

public class SetLength {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello");

        int newLength = -1;
        str.setLength(newLength);

        System.out.println(str.length());
    }
}


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.base/java.lang.AbstractStringBuilder.setLength(AbstractStringBuilder.java:319) at java.base/java.lang.StringBuilder.setLength(StringBuilder.java:85)


StringBuilder setCharAt() in Java

setCharAt(): This method is available in java.lang.StringBuilder class of Java.

Syntax:

void java.lang.AbstractStringBuilder.setCharAt(int index, char ch)

This method takes two arguments one of type int and another of type char as its parameters. The character at the specified index is set to ch.

Note: The index argument must be greater than or equal to 0, and less than the length of this sequence.

Parameters: Two parameters are required for this method.

index: the index of the character to modify.

ch: the new character.

Throws:

StringIndexOutOfBoundsException - if index is negative or greater than or equal to length().

Approach 1: When the index is in the range.

Java

public class SetCharAt {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        int index = 2;
        char ch = 'X';
        str.setCharAt(index, ch);

        System.out.println(str);
    }
}

Output:

HeXlo World


Approach 2: When the index is out of range.

Java

public class SetCharAt {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        int index = 15;
        char ch = 'X';
        str.setCharAt(index, ch);

        System.out.println(str);
    }
}


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: index 15, length 11 at java.base/java.lang.String.checkIndex(String.java:3693) at java.base/java.lang.AbstractStringBuilder.setCharAt(AbstractStringBuilder.java:533) at java.base/java.lang.StringBuilder.setCharAt(StringBuilder.java:85)


StringBuilder reverse() in Java

reverse(): This method is available in java.lang.StringBuilder class of Java.

Syntax:

StringBuilder java.lang.StringBuilder.reverse()

Causes this character sequence to be replaced by the reverse of the sequence.

Let n be the character length of this character sequence(not the length in char values) Then the character at index k in the new character sequence is equal to the character at index n-k-1 in the old character sequence.

Parameters: NA

Returns: a reference to this object which is the reverse of the original object.

Exceptions: NA

For Example:

StringBuilder str = new StringBuilder("Hello World")

str.reverse() = > It returns dlroW olleH.

Approach

Java

public class Reverse {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        System.out.println(str.reverse());
    }
}

Output:

dlroW olleH

StringBuilder replace() in Java

replace(): This method is available in java.lang.StringBuilder class of Java.

Syntax:

StringBuilder java.lang.StringBuilder.replace(int start, int end, String str)

This method takes three arguments, two are of type int and one of type String as its parameters. This method replaces the characters in a substring of this sequence with characters in the specified String. The substring begins at the specified start and extends to the character at index end - 1 or to the end of the sequence if no such character exists.

Note: First the characters in the substring are removed and then the specified String is inserted at the start.

Parameters: Three parameters are required for this method.

start: The beginning index, inclusive.

end: The ending index, exclusive.

str: String that will replace previous contents.

Returns: This object.

Throws:

StringIndexOutOfBoundsException - if start is negative, greater than length(), or greater than end.

For Example:

StringBuilder str = new StringBuilder("Hello World")

int start = 2, end = 7

String str1 = "ABCABC"

str.replace(start,end,str1) = > It returns HeABCABCorld.

Approach 1: When the index is in the range.

Java

public class Replace {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        int start = 2, end = 7;
        String str1 = "ABCABC";
        System.out.println(str.replace(start, end, str1));
    }
}

Output:

HeABCABCorld


Approach 2: When the index is out of range.

Java

public class Replace {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        int start = 10, end = 7;
        String str1 = "ABCABC";
        System.out.println(str.replace(start, end, str1));
    }
}


Output:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: start 10, end 7, length 11 at java.base/java.lang.AbstractStringBuilder.checkRangeSIOOBE(AbstractStringBuilder.java:1802) at java.base/java.lang.AbstractStringBuilder.replace(AbstractStringBuilder.java:995) at java.base/java.lang.StringBuilder.replace(StringBuilder.java:301)


StringBuilder offsetByCodePoints() in Java

offsetByCodePoints(): This method is available in java.lang.AbstractStringBuilder class of Java.

Syntax:

int java.lang.AbstractStringBuilder.offsetByCodePoints(int index, int codePointOffset)

This method takes two arguments of type int as its parameters. This method returns the index within this sequence that is offset from the given index by codePointOffset code points.

Parameters: Two parameters are required for this method.

index: the index to be offset.

codePointOffset: the offset in code points.

Returns: the index within this sequence.

Throws:

IndexOutOfBoundsException - if the index is negative or larger than the length of this sequence,or if codePointOffset is positive and the subsequence starting with index has fewer than codePointOffset code points,or if codePointOffset is negative and the subsequence before index has fewer than the absolute value of codePointOffset code points.

For Example:

StringBuilder str = new StringBuilder("Hello World")

int index = 3

int codePointOffset = 4

str.offsetByCodePoints(index,codePointOffset) = > It returns 7.

Approach 1: When the index is in the range.

Java

public class OffsetByCodePoints {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        int index = 3;
        int codePointOffset = 4;
        System.out.println(str.offsetByCodePoints(index, codePointOffset));

    }
}

Output:

7


Approach 2: When the index is out of range.

Java

public class OffsetByCodePoints {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        int index = -1;
        int codePointOffset = 4;
        System.out.println(str.offsetByCodePoints(index, codePointOffset));

    }
}


Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException at java.base/java.lang.AbstractStringBuilder.offsetByCodePoints(AbstractStringBuilder.java:472) at java.base/java.lang.StringBuilder.offsetByCodePoints(StringBuilder.java:85)


StringBuilder length() in Java

length(): This method is available in java.lang.AbstractStringBuilder class of Java.

Syntax:

int java.lang.AbstractStringBuilder.length()

This method returns the length (character count).

Returns: the length of the sequence of characters currently represented by this object.

Parameters: NA

Exceptions: NA

For Example:

StringBuilder str = new StringBuilder("Hello World")

str.length() = > It returns 11.

Approach

Java

public class Length {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        System.out.println(str.length());

    }
}

Output:

11

StringBuilder lastIndexOf() index in Java

lastIndexOf(): This method is available in java.lang.StringBuilder class of Java.

Syntax:

int java.lang.StringBuilder.lastIndexOf(String str, int fromIndex)

This method takes two arguments, one of type String and another of type int as its parameters. This method returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.

Parameters: Two parameters are required for this method.

str: the substring to search for.fromIndex the index to start the search from.

Returns: the index of the last occurrence of the specified substring, searching backward from the specified index, or -1 if there is no such occurrence.

Exceptions: NA

For Example:

StringBuilder str = new StringBuilder("Hello World")

String str1 = "l"

int fromIndex = 4

str.lastIndexOf(str1,fromIndex) = > It returns 3.

Approach

Java

public class LastIndexOfindex {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        String str1 = "l";
        int fromIndex = 4;
        System.out.println(str.lastIndexOf(str1, fromIndex));
    }
}

Output:

3

StringBuilder lastIndexOf() in Java

lastIndexOf(): This method is available in java.lang.StringBuilder class of Java.

Syntax:

int java.lang.StringBuilder.lastIndexOf(String str)

This method takes one argument of type String as its parameter. This method returns the index within this string of the last occurrence of the specified substring.

Parameters: One parameter is required for this method.

str: the substring to search for.

Returns: the index of the last occurrence of the specified substring, or -1 if there is no such occurrence.

For Example:

StringBuilder str = new StringBuilder("Hello World")

String str1 = "l"

str.lastIndexOf(str1) = > It returns 9.

Approach

Java

public class LastIndexOf {
    public static void main(String[] args) {

        StringBuilder str = new StringBuilder("Hello World");

        String str1 = "l";
        System.out.println(str.lastIndexOf(str1));
    }
}

Output:

9