Sunday, September 3, 2017

Java - StringBuilder Class

Source Link:
https://www.tutorialspoint.com/java/lang/java_lang_stringbuilder.htm

Some Useful Methods:

StringBuilder append(Object obj)
This method appends the string representation of the Object argument.

char charAt(int index)
This method returns the char value in this sequence at the specified index.

StringBuilder delete(int start, int end)
This method removes the characters in a substring of this sequence.

StringBuilder deleteCharAt(int index)
This method removes the char at the specified position in this sequence.

void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Characters are copied from this sequence into the destination character array dst.

int indexOf(String str)
This method returns the index within this string of the first occurrence of the specified substring.

StringBuilder insert(int offset, char c)
This method inserts the string representation of the char argument into this sequence.

StringBuilder insert(int offset, char[] str)
This method inserts the string representation of the char array argument into this sequence.

StringBuilder insert(int offset, Object obj)
This method inserts the string representation of the Object argument into this character sequence.

int length()
This method returns the length (character count).

StringBuilder replace(int start, int end, String str)
This method replaces the characters in a substring of this sequence with characters in the specified String.

StringBuilder reverse()
This method causes this character sequence to be replaced by the reverse of the sequence.

void setCharAt(int index, char ch)
Character at the specified index is set to ch.

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

String toString()
This method returns a string representing the data in this sequence.

Example: 
package com.tutorialspoint;
import java.lang.*;
public class StringBuilderDemo {
   public static void main(String[] args) {
  
      StringBuilder str = new StringBuilder("india");
      System.out.println("string = " + str);

      // reverse characters of the StringBuilder and prints it
      System.out.println("reverse = " + str.reverse());
  
      // reverse is equivalent to the actual
      str = new StringBuilder("malayalam");
      System.out.println("string = " + str);
 
      // reverse characters of the StringBuilder and prints it
      System.out.println("reverse = " + str.reverse());
   }
}

Let us compile and run the above program, this will produce the following result −
string = india 
reverse = aidni 
string = malayalam 
reverse = malayalam

No comments:

Post a Comment

Codility - Lesson 16 Greedy algorithms - 2. MaxNonoverlappingSegments

Source Link: https://app.codility.com/programmers/lessons/16-greedy_algorithms/max_nonoverlapping_segments/ Question: Located on a line ...