Tuesday, November 7, 2017

String class in Java

package MyPackage;

import java.util.ArrayList;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import org.apache.commons.exec.util.StringUtils;



public class StringOperations
{

public static void main(String[] args) {
String mystring="Muttturaj Hulagabal";

char text=mystring.charAt(1);

System.out.println(text);

int count=mystring.length();

System.out.println(count);

String afterTrim=mystring.trim();
System.out.println("Lenght after Trim"+afterTrim.length());

String anotherString="Muttturaj Hulagabal";
System.out.println("0 means true here"+mystring.compareTo(anotherString));

System.out.println("In Bytes here: "+mystring.getBytes());


String suffix="bal";
System.out.println(mystring.endsWith(suffix));

//Substring is important here, it gets Sub string starting from 10th Index
System.out.println("Substring of my string: "+mystring.substring(10));

//Substring is importent here, it gets Sub string starting from 10th Index and ending from 19th Index
System.out.println(mystring.substring(10, 19));


System.out.println(mystring.subSequence(0, 18));

//Add other string to your string
String duplic=mystring.concat(anotherString);
System.out.println(duplic);

//And here we can use campare string with string variable by using == by using intern() Method
if(mystring==new String("Muttturaj Hulagabal").intern())
{
System.out.println("Yes");
}
else
{
System.out.println("NO");
}

//Converting number to string is importent here

int i = 10;
double d=10.00;


//toString() Method is used to convert to String
String s1=Integer.toString(i);
String s2=Double.toString(d);

System.out.println(s1);
System.out.println(s2);

System.out.println(mystring.toLowerCase());

System.out.println(mystring.toUpperCase());

//valueOf() Method is here which will convert defferent types value into String.
int value=10;

String s10=String.valueOf(value);

System.out.println(s10);

//split() is an importent method here in the String class

String string="12345-67890";
String[] parts=string.split("-");
String part1=parts[0];
String part2=parts[1];

System.out.println(part1);
System.out.println(part2);

//org.apache.commons.lang.StringUtils' split method which can split strings based on the character or string you want to split.
String split[]=StringUtils.split(string, "-");

String split1=split[0];
System.out.println(split1);

String split2=split[1];
System.out.println(split2);

//Lets split by "-"

String stringtopart="12-123-1234-12345-123456";

String[] parttomany=stringtopart.split("-");
System.out.println(parttomany.length);

for(int k=0;k {
System.out.println(parttomany[k]);
}


//Lets split by using Array list Java 8

ArrayList stringlist = (ArrayList) Pattern.compile("-").splitAsStream("12-123-1234-12345").collect(Collectors.toList());
System.out.println(stringlist);
for(int l=0;l System.out.println(stringlist.get(l));


}

}


No comments:

Post a Comment