DEV Community

MANOJ K
MANOJ K

Posted on

Java String Methods:

String trim() Method

  • The trim() method is used to remove unwanted spaces from the beginning and end of a string.
  • This method does not change the original string.
//Remove trailing space (password issue)

String pwd = " Admin123 ";
pwd = pwd.trim(); 
System.out.println(pwd);

output:
Admin123
Enter fullscreen mode Exit fullscreen mode

String equalsIgnoreCase() Method

  • The equalsIgnoreCase() method compares two strings, ignoring lower case and upper case differences.
  • This method returns true if the strings are equal, and false if not.
Compare username safely (ignore case)   

String s1 = "Vijay";
String s2 = "vijay";
System.out.println(s1.equalsIgnoreCase(s2));

output:
true
Enter fullscreen mode Exit fullscreen mode

== vs equals() in Java String

  • == is a comparison operator used to check whether two references point to the same memory.
  • equals() is a String method used to check whether two strings have the same content (value).
== vs equals()  

String s1 = "Java";
String s2 = new String("Java");
System.out.println(s1 == s2);         false (memory check)
System.out.println(s1.equals(s2));    true (value check)

Enter fullscreen mode Exit fullscreen mode

contains() method:

  • The contains() method is used to check whether a string contains a specified sequence of characters.
  • Returns true if the characters exist and false if not.
Check email contains '@' and '.'

String email = "test@gmail.com";                
if(email.contains("@") && email.contains(".")){                
  System.out.println("Valid");              
}               
else {              
  System.out.println("invalid");                
}
Enter fullscreen mode Exit fullscreen mode

parseInt() method

  • Integer.parseInt() method is used to convert a String into an integer (int).
Convert String to int   

String num = "12345";       
int n = Integer.parseInt(num);
System.out.println(n+10);

output:
12355
Enter fullscreen mode Exit fullscreen mode

String split() Method:

  • The split() method is used to divide a string into parts based on a delimiter (separator) and returns an array of strings.
Count "Java" occurrences

String str = "Java is easy. Java is powerful.";         
int count = 0;          
String[] words = str.split(" ");            
for(String w : words){                  
if(w.equals("Java")) count++;           
}           
System.out.println(count);

output:
2
Enter fullscreen mode Exit fullscreen mode

Reverse String in Java:

  • String reverse means changing the order of characters from last to first.
public class Main {
    public static void main(String[] args) {

        String str="Java";
        String rev="";

        for(int i=str.length()-1;i>=0;i--){
            rev=rev+str.charAt(i);
        }

        System.out.println("Reversed: "+rev);

    }
}
Enter fullscreen mode Exit fullscreen mode

Check palindrome:

  • A palindrome is a word, number, or string that reads the same forward and backward.
public class Main {
    public static void main(String[] args) {

        String str = "madam";
        String rev = "";

        for(int i=str.length()-1;i>=0;i--){
            rev += str.charAt(i);
        }

        if(str.equals(rev)){
            System.out.println(str+" is Palindrome");
        }
        else{
            System.out.println(str+" is Not Palindrome");
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Remove duplicate characters:

  • This program removes duplicate characters from a string and keeps only unique characters.
public class Main {
    public static void main(String[] args) {

        String str = "aabbccdd";
        String result = "";

        for(int i=0;i<str.length();i++){
            char c=str.charAt(i);

            if(result.indexOf(c)==-1){
                result+=c;
            }
        }

        System.out.println(result);
    }
}
Enter fullscreen mode Exit fullscreen mode

Extract message from log:

  • This program extracts the actual message from a log string by using split() and trim().
String log = "ERROR: File not found";               
String result =log.split(":"[1].trim();             
System.out.println(result);

Enter fullscreen mode Exit fullscreen mode

CSV Extract:

  • This program extracts values from a CSV (Comma Separated Values) string using the split() method.
String data = "Vijay,25,Chennai";
String[] arr = data.split(",");

System.out.println("Name: " + arr[0]);          
System.out.println("Age: " + arr[1]);           
System.out.println("City: " + arr[2]);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)