Showing posts with label string. Show all posts
Showing posts with label string. Show all posts

Java String - Programming Examples

1. How to compare two strings in Java ?

2. How to search the last position of a substring ?

3. How to remove a particular character from a string ?

4. How to replace a substring inside a string by another one ?

5. How to reverse a String?

6. How to search a word inside a string ?

7. How to convert a string totally into upper case?

8. How to optimize string concatenation ?

How to optimize string concatenation ?

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="" p="">         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="" p="">         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 : 22 ms

-------------------------------------------------------------------------------------------------------------

How to do string concatenation ?

Following example shows concatenation string. This method returns a String with the value of the String passed into the method, appended to the end of the String, used to invoke this method.

public class HelloWorld {
   public static void main(String []args) {
      String s = "Hello";
      s = s.concat("word");
      System.out.print(s);
   }
}

Result
The above code sample will produce the following result. The result may vary.

Helloword

How to convert a string totally into upper case?

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 

How to search a word inside a string ?

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

This example shows how we can search a word within a String object

public class HelloWorld {
   public static void main(String[] args) {
      String text = "The cat is on the table";
      System.out.print(text.contains("the"));
   }
}

Result
The above code sample will produce the following result.

true

How to reverse a String?

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

Example

Following another example shows how to reverse a String after taking it from command line argument

import java.io.*;
import java.util.*;

public class HelloWorld {
   public static void main(String[] args) {
      String input = "tutorialspoint";
      char[] try1 = input.toCharArray();
      for (int i = try1.length-1;i>=0;i--) System.out.print(try1[i]);
   }
}

The above code sample will produce the following result.

tniopslairotut 

How to replace a substring inside a string by another one ?

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

How to remove a particular character from a string ?

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.

this is Java

Single Character Functions

C++ supports many character-based input and output functions for reading and writing a character. These functions can read or write one character at a time. These functions are known as unformatted console I/O functions.
Getchar() and Putchar() Functions
The functions getchar() and putchar() are single character functions. The heeader file for these functions is stdio.h.
getchar()
The getchar() function reads a single character from the standard input device( keyboard). The getchar() waits for the character input until a charcter is typed at the keyboard. LEARN MORE>>