You are on page 1of 17

LEARNING OBJECTIVE

o Create code of programming used in general business applications especialy string


manipulation using java programming :
Compare strings,
Search and reverse a substring inside a substring,
Remove and replace a particular character from a string,
Convert a string totally into upper case,
Match regions in a string, optimize string creation,
Format strings and concatenate two strings,
Get unicode of strings and buffer strings.
COMPARE STRINGS
public class StringCompareEmp{
Method public static void main(String args[]){
String str = "Hello World";
compareTo(String anotherString) String anotherString = "hello world";
Summary Object objStr = str;
Compares two strings lexicographically. System.out.println( str.compareTo(anotherString) );
Return int System.out.println( str.compareToIgnoreCase(anotherString) );
System.out.println( str.compareTo(objStr.toString()));
}
}
Method
compareToIgnoreCase(String str)
Summary
Compares two strings lexicographically,
ignoring case differences.
Return int
public class SearchlastString {
SEARCH L AST OCCURANCE public static void main(String[] args) {
String strOrig = "Hello world ,Hello Reader";
The lastIndexOf() method returns the int lastIndex = strOrig.lastIndexOf("Hello");
indexed start position of the string if(lastIndex == - 1){
System.out.println("Hello not found");
passed, starting from the right and }else{
going left. System.out.println("Last occurrence of Hello
is at index "+ lastIndex);
}
}
}
REMOVE CHARACTER public class Main {
public static void main(String args[]) {
substring(int beginx) String str = "this is Java";
System.out.println(removeCharAt(str, 3));
Returns a new string that is a }
substring of this string. public static String removeCharAt(String s, int pos) {
return s.substring(0, pos) + s.substring(pos + 1);
substring(int beginx, int endx) }
}
Returns a new string that is a
substring of this string.
REPLACE A SUBSTRING
replace(char oldChar, char newChar) public class StringReplaceEmp{
Returns a new string resulting from replacing all public static void main(String args[]){
occurrences of oldChar in this string with newChar.
String str="Hello World";
replace(CharSequence target, CharSequence replacement)
System.out.println( str.replace( 'H','W' ) );
Replaces each substring of this string that matches the
literal target sequence with the specified literal System.out.println( str.replaceFirst("He", "Wa") );
replacement sequence. System.out.println( str.replaceAll("He", "Ha") );
replaceAll(String regex, String replacement) }
Replaces each substring of this string that matches the }
given regular expression with the given replacement.
replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches
the given regular expression with the given replacement
public class StringReverseExample{
REVERSE A STRING public static void main(String[] args){
String string="abcdef";
toString() String reverse = new StringBuffer(string).
This object (which is already a reverse().toString();
string) is itself returned. System.out.println("\nString before reverse:
"+string);
System.out.println("String after reverse:
"+reverse);
}
}
SEARCH A WORD public class SearchStringEmp{
public static void main(String[] args) {
indexOf(int ch) String strOrig = "Hello readers";
Returns the index within this string of the first int intIndex = strOrig.indexOf("Hello");
occurrence of the specified character. if(intIndex == - 1){
indexOf(int ch, int fromIndex) System.out.println("Hello not found");
Returns the index within this string of the first }else{
occurrence of the specified character, starting System.out.println("Found Hello at index +
the search at the specified index. intIndex);
indexOf(String str) }
Returns the index within this string of the first }
occurrence of the specified substring.
}
indexOf(String str, int fromIndex)
Returns the index within this string of the first
occurrence of the specified substring, starting at
the specified index.
public class JavaStringSplitEmp{
public static void main(String args[]){
String str = "jan-feb-march";
String[] temp;
String delimeter = "-";
temp = str.split(delimeter);
for(int i =0; i < temp.length ; i++){
SPLIT A STRING System.out.println(temp[i]);
System.out.println("");
split(String regex) str = "jan.feb.march";
Splits this string around matches of delimeter = "\\.";
the given regular expression. temp = str.split(delimeter);
}
split(String regex, int limit) for(int i =0; i < temp.length ; i++){
Splits this string around matches of System.out.println(temp[i]);
the given regular expression. System.out.println("");
temp = str.split(delimeter,2);
for(int j =0; j < temp.length ; j++){
System.out.println(temp[i]);
}
}
}
}
CONVERT A STRING
public class StringToUpperCaseEmp {

toUpperCase() public static void main(String[] args) {


String str = "string abc touppercase ";
Converts all of the characters in String strUpper = str.toUpperCase();
this String to upper case using the System.out.println("Original String: " + str);

rules of the default locale. System.out.println("String changed to upper case: "


+ strUpper);
toUpperCase(Locale locale) }
}
Converts all of the characters in
this String to upper case using the
rules of the given Locale.
MATCH REGIONS IN A
STRING public class StringRegionMatch{
public static void main(String[] args){
regionMatches(boolean ignoreCase, String first_str = "Welcome to Microsoft";
int toffset, String other, int ooffset, String second_str = "I work with Microsoft";
boolean match = first_str.regionMatches(11,
int len) second_str, 12, 9);
Tests if two string regions are System.out.println("first_str[11 -19] == "+
equal. "second_str[12 - 21]:-"+ match);
}
regionMatches(int toffset, String other, }
int ooffset, int len)
Tests if two string regions are
equal.
public class StringComparePerformance{
public static void main(String[] args){
long startTime = System.currentTimeMillis();
for(int i=0;i<50000;i++){

COMPARE PERFORMANCE OF String s1 = "hello";


String s2 = "hello";
T WO STRINGS }
long endTime = System.currentTimeMillis();
currentTimeMillis() System.out.println("Time taken for creation"
+ " of String literals : "+ (endTime - startTime)
Returns the current time in
+ " milli seconds" );
milliseconds. Note that while the long startTime1 = System.currentTimeMillis();
unit of time of the return value is for(int i=0;i<50000;i++){
a millisecond, the granularity of the String s3 = new String("hello");
value depends on the underlying String s4 = new String("hello");
}
operating system and may be long endTime1 = System.currentTimeMillis();
larger. For example, many operating System.out.println("Time taken for creation"
systems measure time in units of + " of String objects : " + (endTime1 - startTime1)
tens of milliseconds. + " milli seconds");
}
}
public class StringOptimization{
public static void main(String[] args){
String variables[] = new String[50000];
for( int i=0;i <50000;i++){
variables[i] = "s"+i;
}
long startTime0 = System.currentTimeMillis();
for(int i=0;i<50000;i++){
variables[i] = "hello";
}
OPTIMIZE STRING CREATION long endTime0 = System.currentTimeMillis();
System.out.println("Creation time"
+ " of String literals : "+ (endTime0 - startTime0)
+ " ms" );
long startTime1 = System.currentTimeMillis();
for(int i=0;i<50000;i++){
variables[i] = new String("hello");
}
long endTime1 = System.currentTimeMillis();
System.out.println("Creation time of"
+ " String objects with 'new' key word : "
+ (endTime1 - startTime1)
+ " ms");
long startTime2 = System.currentTimeMillis();
for(int i=0;i<50000;i++){
variables[i] = new String("hello");
variables[i] = variables[i].intern();
}
long endTime2 = System.currentTimeMillis();
System.out.println("Creation time of"
+ " String objects with intern(): "
+ (endTime2 - startTime2)
+ " ms");
}
}
FORMAT STRINGS
import java.util.*;

format(Locale l, String format, Object public class StringFormat{


args) public static void main(String[] args){
Returns a formatted string using double e = Math.E;
System.out.format("%f%n", e);
the specified locale, format string, System.out.format(Locale.GERMANY, "%-10.4f%n%n", e);
and arguments. }
format(String format, Objectargs) }

Returns a formatted string using


the specified format string and
arguments.

See : https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html
public class StringConcatenate{
public static void main(String[] args){
long startTime = System.currentTimeMillis();
for(int i=0;i<5000;i++){
String result = "This is"
+ "testing the"
+ "difference"+ "between"

CONCATENATE T WO STRINGS
+ "String"+ "and"+ "StringBuffer";
}
long endTime = System.currentTimeMillis();
String buffers are safe for use by multiple System.out.println("Time taken for string"
threads. The methods are synchronized where + "concatenation using + operator : "
necessary so that all the operations on any + (endTime - startTime)+ " ms");
long startTime1 = System.currentTimeMillis();
particular instance behave as if they occur in
for(int i=0;i<5000;i++){
some serial order that is consistent with the StringBuffer result = new StringBuffer();
order of the method calls made by each of the result.append("This is");
individual threads involved. result.append("testing the");
The principal operations on a StringBuffer are result.append("difference");
the append and insert methods, which are result.append("between");
overloaded so as to accept data of any type. result.append("String");
Each effectively converts a given datum to a result.append("and");
string and then appends or inserts the result.append("StringBuffer");
characters of that string to the string buffer. }
The append method always adds these long endTime1 = System.currentTimeMillis();
System.out.println("Time taken for String concatenation"
characters at the end of the buffer; the insert
+ "using StringBuffer : "
method adds the characters at a specified + (endTime1 - startTime1)+ " ms");
point. }
}
GET UNICODE OF STRINGS public class StringUniCode{
public static void main(String[] args){
codePointBefore(int i) String test_string="Welcome to TutorialsPoint";

Returns the character (Unicode System.out.println("String under test is =


"+test_string);
code point) before the specified System.out.println("Unicode code point at"
index. The index refers to char +" position 5 in the string is = "
values (Unicode code units) and + test_string.codePointBefore(5));

ranges from 1 to length. }


}
public class StringBuffer{
public static void main(String[] args) {
private static void countTo_N_Improved();
}
private final static int MAX_LENGTH=30;
BUFFER STRINGS private static String buffer = "";
private static void emit(String nextChunk) {
if(buffer.length() + nextChunk.length() > MAX_LENGTH) {
System.out.println(buffer);
buffer = "";
}
buffer += nextChunk;
}
private static final int N=100;
private static void countTo_N_Improved() {
for (int count=2; count7lt;=N; count=count+2) {
emit(" " + count);
}
}
}
ThankYOU...

You might also like