Download Problem Description

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Problem Description:
How to replace a substring inside a string by another one ?
Solution:
This example describes how replace method of java String class can be used to replace character
or substring by new one.
public class StringReplaceEmp{
public static void main(String args[]){
String str="Hello World";
System.out.println( str.replace( 'H','W' ) );
System.out.println( str.replaceFirst("He", "Wa") );
System.out.println( str.replaceAll("He", "Ha") );
}
}
Result:
The above code sample will produce the following result.
Wello World
Wallo World
Hallo World
Problem Description:
How to search the last position of a substring ?
Solution:
This example shows how to determine the last position of a substring inside a string with the
help of strOrig.lastIndexOf(Stringname) method.
public class SearchlastString {
public static void main(String[] args) {
String strOrig = "Hello world ,Hello Reader";
int lastIndex = strOrig.lastIndexOf("Hello");
if(lastIndex == - 1){
System.out.println("Hello not found");
}else{
System.out.println("Last occurrence of Hello
is at index "+ lastIndex);
}
}
}
Result:
The above code sample will produce the following result.
Last occurrence of Hello is at index 13
Problem Description:
How to remove a particular character from a string ?
Solution:
Following example shows hoe to remove a character from a particular position from a string with
the help of removeCharAt(string,position) method.
public class Main {
public static void main(String args[]) {
String str = "this is Java";
System.out.println(removeCharAt(str, 3));
}
public static String removeCharAt(String s, int pos) {
return s.substring(0, pos) + s.substring(pos + 1);
}
}
Result:
The above code sample will produce the following result.
thi is Java
Problem Description:
How to compare two strings ?
Solution:
Following example compares two strings by using str compareTo (string) , str
compareToIgnoreCase(String) and str compareTo(object string) of string class and returns the
ascii difference of first odd characters of compared strings .
public class StringCompareEmp{
public static void main(String args[]){
String str = "Hello World";
String anotherString = "hello world";
Object objStr = str;
System.out.println( str.compareTo(anotherString) );
System.out.println( str.compareToIgnoreCase(anotherString) );
System.out.println( str.compareTo(objStr.toString()));
}
}
Result:
The above code sample will produce the following result.
-32
0
0
Problem Description:
How to reverse a String?
Solution:
Following example shows how to reverse a String after taking it from command line argument
.The program buffers the input String using StringBuffer(String string) method, reverse the
buffer and then converts the buffer into a String with the help of toString() method.
public class StringReverseExample{
public static void main(String[] args){
String string="abcdef";
String reverse = new StringBuffer(string).
reverse().toString();
System.out.println("\nString before reverse:
"+string);
System.out.println("String after reverse:
"+reverse);
}
}
Result:
The above code sample will produce the following result.
String before reverse:abcdef
String after reverse:fedcba
Problem Description:
How to search a word inside a string ?
Solution:
This example shows how we can search a word within a String object using indexOf() method
which returns a position index of a word within the string if found. Otherwise it returns -1.
public class SearchStringEmp{
public static void main(String[] args) {
String strOrig = "Hello readers";
int intIndex = strOrig.indexOf("Hello");
if(intIndex == - 1){
System.out.println("Hello not found");
}else{
System.out.println("Found Hello at index "
+ intIndex);
}
}
}
Result:
The above code sample will produce the following result.
Found Hello at index 0
Problem Description:
How to split a string into a number of substrings ?
Solution:
Following example splits a string into a number of substrings with the help of str split(string)
method and then prints the substrings.
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++){
System.out.println(temp[i]);
System.out.println("");
str = "jan.feb.march";
delimeter = "\\.";
temp = str.split(delimeter);
}
for(int i =0; i < temp.length ; i++){
System.out.println(temp[i]);
System.out.println("");
temp = str.split(delimeter,2);
for(int j =0; j < temp.length ; j++){
System.out.println(temp[i]);
}
}
}
}
Result:
The above code sample will produce the following result.
jan
feb
march
jan
jan
jan
feb.march
feb.march
feb.march
Problem Description:
How to convert a string totally into upper case?
Solution:
Following example changes the case of a string to upper case by using String toUpperCase()
method.
public class StringToUpperCaseEmp {
public static void main(String[] args) {
String str = "string abc touppercase ";
String strUpper = str.toUpperCase();
System.out.println("Original String: " + str);
System.out.println("String changed to upper case: "
+ strUpper);
}
}
Result:
The above code sample will produce the following result.
Original String: string abc touppercase
String changed to upper case: STRING ABC TOUPPERCASE
Problem Description:
How to match regions in strings ?
Solution:
Following example determines region matchs in two strings by using regionMatches() method.
public class StringRegionMatch{
public static void main(String[] args){
String first_str = "Welcome to Microsoft";
String second_str = "I work with Microsoft";
boolean match = first_str.
regionMatches(11, second_str, 12, 9);
System.out.println("first_str[11 -19] == "
+ "second_str[12 - 21]:-"+ match);
}
}
Result:
The above code sample will produce the following result.
first_str[11 -19] == second_str[12 - 21]:-true
Problem Description:
How to match regions in strings ?
Solution:
Following example determines region matchs in two strings by using regionMatches() method.
public class StringRegionMatch{
public static void main(String[] args){
String first_str = "Welcome to Microsoft";
String second_str = "I work with Microsoft";
boolean match = first_str.
regionMatches(11, second_str, 12, 9);
System.out.println("first_str[11 -19] == "
+ "second_str[12 - 21]:-"+ match);
}
}
Result:
The above code sample will produce the following result.
first_str[11 -19] == second_str[12 - 21]:-true
Problem Description:
How to compare performance of string creation ?
Solution:
Following example compares the performance of two strings created in two different ways.
public class StringComparePerformance{
public static void main(String[] args){
long startTime = System.currentTimeMillis();
for(int i=0;i<50000;i++){
String s1 = "hello";
String s2 = "hello";
}
long endTime = System.currentTimeMillis();
System.out.println("Time taken for creation"
+ " of String literals : "+ (endTime - startTime)
+ " milli seconds" );
long startTime1 = System.currentTimeMillis();
for(int i=0;i<50000;i++){
String s3 = new String("hello");
String s4 = new String("hello");
}
long endTime1 = System.currentTimeMillis();
System.out.println("Time taken for creation"
+ " of String objects : " + (endTime1 - startTime1)
+ " milli seconds");
}
}
Result:
The above code sample will produce the following result.The result may vary.
Time taken for creation of String literals : 0 milli seconds
Time taken for creation of String objects : 16 milli seconds
Problem Description:
How to optimize string creation ?
Solution:
Following example optimizes string creation by using String.intern() method.
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";
}
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");
}
}
Result:
The above code sample will produce the following result.The result may vary.
Creation time of String literals : 0 ms
Creation time of String objects with 'new' key word : 31 ms
Creation time of String objects with intern(): 16 ms
Problem Description:
How to format strings ?
Solution:
Following example returns a formatted string value by using a specific locale, format and
arguments in format() method
import java.util.*;
public class StringFormat{
public static void main(String[] args){
double e = Math.E;
System.out.format("%f%n", e);
System.out.format(Locale.GERMANY, "%-10.4f%n%n", e);
}
}
Result:
The above code sample will produce the following result.
2.718282
2,7183
Problem Description:
How to optimize string concatenation ?
Solution:
Following example shows performance of concatenation by using "+" operator and
StringBuffer.append() method.
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"
+ "String"+ "and"+ "StringBuffer";
}
long endTime = System.currentTimeMillis();
System.out.println("Time taken for string"
+ "concatenation using + operator : "
+ (endTime - startTime)+ " ms");
long startTime1 = System.currentTimeMillis();
for(int i=0;i<5000;i++){
StringBuffer result = new StringBuffer();
result.append("This is");
result.append("testing the");
result.append("difference");
result.append("between");
result.append("String");
result.append("and");
result.append("StringBuffer");
}
long endTime1 = System.currentTimeMillis();
System.out.println("Time taken for String concatenation"
+ "using StringBuffer : "
+ (endTime1 - startTime1)+ " ms");
}
}
Result:
The above code sample will produce the following result.The result may vary.
Time taken for stringconcatenation using + operator : 0 ms
Time taken for String concatenationusing StringBuffer : 16 ms
Problem Description:
How to determine the Unicode code point in string ?
Solution:
This example shows you how to use codePointBefore() method to return the character (Unicode
code point) before the specified index.
public class StringUniCode{
public static void main(String[] args){
String test_string="Welcome to TutorialsPoint";
System.out.println("String under test is = "+test_string);
System.out.println("Unicode code point at"
+" position 5 in the string is = "
+ test_string.codePointBefore(5));
}
}
Result:
The above code sample will produce the following result.
String under test is = Welcome to TutorialsPoint
Unicode code point at position 5 in the string is =111
Problem Description:
How to buffer strings ?
Solution:
Following example buffers strings and flushes it by using emit() method.
public class StringBuffer{
public static void main(String[] args) {
countTo_N_Improved();
}
private final static int MAX_LENGTH=30;
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; count<=N; count=count+2) {
emit(" " + count);
}
}
}
Result:
The above code sample will produce the following result.
2 4 6
24 26
44 46
64 66
8 10 12 14 16 18 20 22
28 30 32 34 36 38 40 42
48 50 52 54 56 58 60 62
68 70 72 74 76 78 80 82