10 most useful string methods in Java

10 most useful string methods in Java

Introduction to Strings

String is an object that represents sequence of char values. Strings are immutable in Java. There are two ways to create string in Java

  • By String literal
  • By new keyword
String myString1 = "Pankaj Singh";
String myString2 = new String("Pankaj");

here, i have used my name as a string you can take any other example

Note: String literal create no new object if it exists already in the string constant pool (SCP) which is a special place for all strings in heap memory. Create string of same object using new keyword.This will create new object outside the string pool if it already exist in it

Image of Spring pool in java

Note I want you guys to try it for yourself instead to only copy and pasting.

String methods in Java

indexOf()

indexOf() used to find characters and substrings in a string. It returns the index of first occurrence from left of the passed string or character

syntax - public int indexOf​(String str, int fromIndex)

  • str - substring to be search
  • fromIndex - search begin from this index

search "world" in "Hello world!" string

  • str = "Hello world!"
  • target = "world"

    int firstOccurence(String str, String target){
    
         return str.indexOf(target);
    }
    //return index of first occurence of target
    

toCharArray()

toCharArray() used to form a character array of a string

syntax - public char[ ] toCharArray()

Example : check if string is palindrome of not

//palindrome = "taccat"

boolean checkPalindrome(String palindrome){
char[] chArr = palindrome.toCharArray();
int len = palindrome.length();
for(int i=0; i<len; i++){
     if(chArr[i] != chArr[len-i-1]){
                 return false;
        }
    }
}

charAt()

charAt() Used to find the character at particular index

syntax - public char charAt​(int index)

Example: count no. of spaces in the string

String str = "Upskill by learn by doing"
int len = str.length();
int count = 0;
for(int i=0; i<len; i++){
      if (str.charAt(i) == " " ) count++;
}
System.out.println(count); //4

concat()

concat() Used to concatenate two strings

syntax - public String concat(String str)

Example : concatenate last name and firstname

String firstName = "Jon";
String lastName = "snow";
String fullName = firstName.concat(lastName);
System.out.println(fullName); //Jon snow

replace()

replace() Used for replacing characters and substrings in a string

syntax - public String replace​(char oldChar, char newChar)

Example : remove all white spaces from the string

String str = "remove all whitespaces from this string";
String newStr = str.replace(" ", "");
System.out.println(newStr);

substring()

substring() Used to extract a portion of a string from original string

syntax - public String substring​(int beginIndex, int endIndex)

Example : print first 3 character of a string

String str = "God is almighty";
System.out.println(str.substring(0, 3)); //God

split()

split() Used to breaks a given string around matches of the given regular expression.After splitting against the given regular expression, this method returns a char array

syntax - public String[] split​(String regex, int limit)

limit : number of strings return after split

String str = "123-456-789";
String[] arrOfStr = str.split("-", 2);
for (String a :  arrOfStr)
       System.out.println(a);
//123
//456-789

compareTo()

compareTo() It compares the given string with the current string lexicographically. It returns a positive number, negative number, or 0

  • if s1 > s2, returns +ve number
  • if s1 < s2, returns -ve number
  • if s1 == s2, returns 0

syntax : public int compareTo(String anotherString)

String s1 = "hello";
String s2 = "hello";
String s3 = "world";
String s4 = "gg";
System.out.println(s1.compareTo(s2)); //0 because both are equal
System.out.println(s1.compareTo(s3)); //-15 because "h" is 15 times lower than "w"
System.out.println(s1.compareto(s4)); //1 because "h" is 1 times greater than "g"

strip()

strip() To eliminate all trailing and leading whitespaces from the given string

syntax - public String strip()

Example

String s1 = " Hello World ";
System.out.println(s1.strip()); //Hello World

valueOf()

valueOf() Used to return string representation of passed argument

syntax - public static String valueOf​(char[] data)

Note : valueOf() has many overloaded variants that aid in the conversion of almost any primitive form to string

char array[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
System.out.println(String.valueOf(array)); //abcdefg