String : A built in class, whose object is used to store the set of characters, is called as string.
Example :
String S1=new String("Hello");
or
String S1="Hello";
Example :
String S1=new String("Hello");
or
String S1="Hello";
String manipulation methods:
- length() :- This method is used to return the number of characters of a given string.
- trim() :- This method is used to trim or remove the white spaces from Right Hand Side and Left Hand Side of given string.
- toUpperCase() :- This method is used to convert the given string in Upper case.
- toLowerCase() :- This method is used to convert the given string in Lower case.
- equals() :- This method is used to compare two string according to there ASCII value for equality.
[It returns true if both the string are same & otherwise return false]
- CompareTo() :- This method is also used to compare two string according to ASCII values.
[It's return type is Integer]
Example:
int i=s1.compareTo(s2);
if it return > 0 value then s2>s1
if it return < 0 value then s1>s2
if it return = 0 value then s1=s2
- CompareToIgnoreCase() :- It work is same as above method with ignoring the case sensitivity.
Write a program to implement all the methods of string class.
class str { public static void main(String args[]) { String s1="Good morning"; System.out.println(s1); String s2=s1.trim(); System.out.println(s2); System.out.println("length of s1="+s1.length()); System.out.println("length of s2="+s2.length()); String s3=s2.toUpperCase(); String s4=s2.toUpperCase(); System.out.println("S3= "+s3); System.out.println("S4= "+s4); if(s3.equals(s4)) System.out.println("Both the string are same"); else System.out.println("Both the string are not same"); int i=s3.compareToIgnoreCase(s4); if(i<0 s4="" system.out.println="">s3"); else if(i>0) System.out.println("s3>s4"); else if(i==0) System.out.println("s3 = s4"); } } 0>
StringBuffer class methods
- append(String) :- This method is used to join or append the new string in previous string.
- insert(index, string) :- This method is used to insert the new string on the specified index of previous string.
- setCharAt(index, char) :- This method set or replace the specified index character with the new character.
- reverse() :- This method is used to convert the given string in reverse.
Write a program to implement all the methods of stringBuffer class.
class str1 { public static void main(String args[]) { StringBuffer sb=new StringBuffer("Hello morning"); System.out.println(sb); sb.append("Bye"); System.out.println(sb); sb.insert(13, " "); System.out.println(sb); sb.insert(6, "Good"); System.out.println(sb); sb.insert(10, " ") System.out.println(sb); sb.setCharAt(10,"_"); System.out.println(sb); System.out.println(sb.reverse()); } }
Post A Comment: