String methods


String methods

The java.lang.String class provides various list of methods to perform operations to alter and manipulate on sequence of char values. Some of these methods are listed below

1) String length():

This methods returns the total length of the string or total number of character in string

Example No.1:

Com.knowledge2life public class Main { public static void main(String[] args) { String txt = "ABCDEFGHIJKLMNQRSTUVWXYZ"; System.out.println("Knowledge2life "); System.out.println("Length is: "+txt.length()); } }

OUTPUT:

Knowledge2life
Length is: 24

2) String concat():

Concat() method is used to return a combined string or can be also used as an alternative to “+” operator

3) String Substring():

substring() method return character of string based on the index the start index and end index

4) String Split():

String Split() method is used to detach or split string by the given expression and is stored in String Array

5) String IsEmpty():

this method is use to check if the string is empty or not and return bollean value if not empty then False or if empty then True.

6) String join():

The join method returns a new formed string from the string array and the character that is to joined with.

7) String contains(CharSequence s):

The method return boolean to find the character sequence in a string if character is available it will return true and if not then False.

8) String Trim():

Trim() method is used to remove leading and trailing space in a string.

9) String toUpperCase():

The toUpperCase() is to change all String character to upper case.

10) String toLowerCase():

The toLowerCase() is to change all String character to lower case.

Example:

Com.knowledge2life public class Main { public static void main(String[] args) { String txt = "KnoWledge2Life"; System.out.println(txt.toUpperCase()); System.out.println(txt.toLowerCase()); } }

OUTPUT:

KNOWLEDGE2LIFE
Knowledge2life

11) String replace() :

The Replace method is use to replace the substring with another substring or character.

12) String equals()  :

The equals() method return boolean value based on the two string it compares the character of both string and if they are same the returns True and if not the False

13) Java String endsWith() :

The endsWith() method also returns a boolean type whenever the suffix matches the end of the string it returns True and False

Example No:

Com.knowledge2life public class Main{ public static void main(String args[]){ String s3=""; String s1="Knowledge2life"; String s2="Knowledge2life1"; //Replace method String replaceString=s1.replace('d','t'); System.out.println(replaceString); //Contain method System.out.println(s1.contains("life")); // Equal method System.out.println(s1.equalsIgnoreCase(s2)); //Endwith method System.out.println(s1.endsWith("e")); //TocharArray char[] ch=s1.toCharArray(); for(int i=0;i <ch.length;i++){ System.out.print(ch[i]); } } }

OUTPUT:

Knowletge2life
True
False
True
Knowledge2life