Showing posts with label Strings. Show all posts
Showing posts with label Strings. Show all posts

StringBuffer in Java

The StringBuffer class is similar to String class and something more. The string class creates fixed length  while StringBuffer can create flexible length that can be altered in terms of length and content and also provides ability to modify the actual string.

Let us look at the following example which uses the StringBuffer class to replace the content of StringBuffer object from “Hello word” to “Hello java”.

public class sample
{
            public static void main(String args[])
                        {
                                    StringBuffer sb = new StringBuffer(“Hello word”);
                                    sb.replace(6,10,”java”);
                                    System.out.println(sb);
                        }
}

Output
Hello java

StringBuffer class methods

The following table demonstrates list of methods that can be used for string manipulation.



Method
Meaning
1
StringBuffer append(String st)
Appends the string to the string buffer.
2
StringBuffer delete(int start, int end)
Removes substring starting from start up to end of the string buffer.
3
StringBuffer insert(int pos, String st)
Insert the String into the string buffer
4
StringBuffer replace(int start, int end, String st)
Replace substring starting from start up to end of the string buffer.
5
StringBuffer reverse()
Returns reverse sequence of character of string buffer

Java Programming Example to check whether the given string is palindrome or not?

This program will accept string from the user through keyboard and display whether the given string is palindrome or not.

import java.io.*;

/**
 *
 * @author JavaHotSpot
 */

public class palindrome
{
  public static void main(String args[])
 {
     String s1,s2;
     int length;
     DataInputStream d;
     try
     {
     System.out.println("Enter the String");
     d=new DataInputStream(System.in);
     s1=(String)d.readLine();
     StringBuffer sb;
     sb=new StringBuffer(s1);
     s2=sb.reverse().toString();
     System.out.println("The Reverse of the string is "+s2);
     if(s1.equals(s2))
     {
         System.out.println("The given string is palindrome");
     }
     else
     {
         System.out.println("The given string is not palindrome");
     }
     }
     catch(Exception e)
     {
         System.out.println(e.toString());
     }
 }
}

Output:

Run 1:
Enter the String
Javaatweet
The Reverse of the string is teewaavaJ
The given string is not palindrome

Run 2:
Enter the String
madam
The Reverse of the string is madam
The given string is palindrome

StringTokenizer in Java

StringTokenizer allows you to specify a delimiter as a set of characters and matches any number or combination of those characters as a delimiter between tokens. The following code snippet reads the words:

    String str = "Java is object oriented language”;

    StringTokenizer st = new StringTokenizer(str);

    while (st.hasMoreTokens())
               {
               String word = st.nextToken();
               ...
               }

We invoke the hasMoreTokens( ) and nextToken( ) methods to loop over the words of the text. By default, the StringTokenizer class uses standard whitespace characterscarriage return, newline, and tabas delimiters. You can also specify your own set of delimiter characters in the StringTokenizer constructor. Any contiguous combination of the specified characters that appears in the target string is skipped between tokens:

Example:

import java.util.StringTokenizer;

/**
 *
 * @author JavaHotSpot
 */

public class StringTonenizers
{
  public static void main(String args[])
  {
      String str = "Apple,Orange,Banana,Mango,pinaple";
      StringTokenizer st;
      st=new StringTokenizer(str,",");
      while(st.hasMoreTokens())
      {
          System.out.println(st.nextToken());
      }
  }
}

Output:
Apple
Orange
Banana
Mango

Split in Java

The String split( ) method accepts a regular expression that describes a delimiter and uses it to chop the string into an array of Strings:

String str = "Apple,Orange,Banana,Mango,pinaple ";
String[] results = str.split(",");
 
The split() method on the String class accepts a regular expression as its only parameter, and will return an array of String objects split according to the rules of the passed-in regular expression. This makes parsing a comma-separated string an easy task. In this phrase, we simply pass a comma into the split() method, and we get back an array of strings containing the comma-separated data. So the results array in our phrase would contain the following content:

results[0] = Apple
results[1] = Orange
results[2] = Banana
results[3] = Mango
results[4] = pinaple
 
Example:
 
 
/**
 *
 * @author JavaHotSpot
 */
 
public class StringSplit
{
  public static void main(String args[])
  {
      String str = "Apple,Orange,Banana,Mango,pinaple";
      String[] results=str.split(",");
      for(int i=0;i<results.length;i++)
      {
          System.out.println(results[i]);
      }
  }
}
 
Output:
Apple
Orange
Banana
Mango

Scanner Class in Java

The Scanner class lets you read an input source by tokens, somewhat analogous to the StreamTokenizer . The Scanner is more flexible in some ways—it lets you break tokens based on spaces or regular expressions—but less in others—you need to know the kind of token you are reading. In the Scanner you specify the input token types by calling methods like nextInt( ), nextDouble( ), and so on. Here is a simple example of scanning:

//From sampleScanner.java
String str = "12,Gautam,98.45";
            Scanner sc = new Scanner(str).useDelimiter(",");
            roll=sc.nextInt();
            name=sc.next();
            percentage=sc.nextFloat();

The Scanner is convenient because it can read not only from Strings but directly from stream sources, such as InputStreams, Files, and Channels:

    Scanner fileScanner = new Scanner( new File("spreadsheet.txt") );
    fileScanner.useDelimiter( “,”);
    // ...

Another thing that you can do with the Scanner is to look ahead with the "hasNext" methods to see if another item is coming:

    while( scanner.hasNextInt(  ) )
{
      int n = scanner.nextInt(  );
      ...
 }

The following table provides different scanner methods.

Scanner methods
Returned type
"has" method
"next" method
Comment
String
hasNext( )
next( )
The next complete token from this scanner
String
hasNext(Pattern)
next(Pattern)
The next string that matches the given regular expression (regex)
String
hasNext(String)
next(String)
The next token that matches the regex pattern constructed from the specified string
BigDecimal
hasNextBigDecimal( )
nextBigDecimal( )
The next token of the input as a BigDecimal
BigInteger
hasNextBigInteger(   )
nextBigInteger(   )
The next token of the input as a BigInteger
boolean
hasNextBoolean( )
nextBoolean( )
The next token of the input as a boolean
byte
hasNextByte( )
nextByte( )
The next token of the input as a byte
double
hasNextDouble( )
nextDouble( )
The next token of the input as a double
float
hasNextFloat( )
nextFloat( )
The next token of the input as a float
int
hasNextInt( )
nextInt( )
The next token of the input as an int
String
N/A
nextLine( )
Reads up to the end-of-line, including the line ending
long
hasNextLong( )
nextLong( )
The next token of the input as a long
short
hasNextShort( )
nextShort( )
The next token of the input as a short


Example:

import java.util.Scanner;
/**
 *
 * @author J a v a a t w e e t
 */

public class ScannerExample
{
  public static void main(String args[])
  {
      int roll;
      String name;
      float percentage;
      String str = "12,Gautam,98.45";
      Scanner sc = new Scanner(str).useDelimiter(",");
      roll=sc.nextInt();
      name=sc.next();
      percentage=sc.nextFloat();
      System.out.println(roll+"\n"+name+"\n"+percentage);
  }
}

Output:
12
Gautam
98.45