String Functions of Java

//String Functions
public class StrDemo
{
public static void main(String args[])
{
int len;

//Ways of String initializations
String s1="Hello Everybody";
String s2=new String("Hi Everybody");
String s3=new String(s1);
String s4=s1;
String tmp;

//Length Function of String.
len=s1.length();
System.out.println("Length of: '"+s1+"' is "+len);
System.out.println("Length of: '"+s2+"' is "+s2.length());

//Comparision Functions of String
System.out.println("String1 is: "+s1);
System.out.println("String2 is: "+s2);
System.out.println("String3 is: "+s3);
System.out.println(s1.compareTo(s2));
System.out.println(s3.compareTo(s1));

//Comparision Functions of String
System.out.println(s1.equals(s2));
System.out.println(s3.equals(s1));

s4=s1.concat(s2);
System.out.println("S4 = "+s4);


//Finding Index of Character in String.
char ch;
ch='o';
int n;
n=s1.indexOf(ch);
System.out.println("Character: "+ch+" is at index: "+n+" in string1");
n=s1.indexOf(ch,5);
System.out.println("Character: "+ch+" is at index: "+n+" in string1");
n=s1.lastIndexOf(ch);
System.out.println("Character: "+ch+" is at index: "+n+" in string1");

//String Starts with
s4="Hello";
boolean ans;
ans=s1.startsWith(s4);
System.out.println("String1 starts with "+s4+": "+ans);

//String Ends with
s4="bodies";
ans=s1.endsWith(s4);
System.out.println("String1 ends with "+s4+": "+ans);

//Change Case of Strings.
s4=s1.toUpperCase();
System.out.println("S4 = "+s4);
s4=s1.toLowerCase();
System.out.println("S4 = "+s4);

//Replace string.
s4="The green bottle is in green bag.";
System.out.println("S4 = "+s4);
s4=s4.replace("green","red");
System.out.println("S4 = "+s4);

//Searching in String.
tmp="Hello";
ans=s1.contains(tmp);
System.out.println("S1 contains: "+tmp+": "+ans);

//Slicing the String.
System.out.println("S4 = "+s4);
s4=s4.substring(4,9);
System.out.println("S4 = "+s4);

//Check string is empty or  not.
s4="";
ans=s4.isEmpty();
System.out.println("String4 is Empty: "+ans);

//Trimming the String.
s4="   Computer    ";
len=s4.length();
System.out.println("Before Trim: "+s4+", Length: "+len);
s4=s4.trim();
len=s4.length();
System.out.println("After Trim: "+s4+", Length: "+len);

//Converting integer to string.
len=12345;
s4=s4.valueOf(len);
System.out.println("S4 = "+s4);

//Converting String to Integer
s4="36598";
len=Integer.valueOf(s4);
System.out.println("Len = "+len);

//Converting String to Double
double x;
s4="986598.265689";
x=Double.valueOf(s4);
System.out.println("X = "+x);
}
}



No comments

Post your comments

Powered by Blogger.