Home Java Javatutorial SubString in Java
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

SubString in Java

Advertisement
SubString(), a method of String class is used to get a part of original string as String object. This method is defined in java.lang.String class. This method returns part of String started from beginIndex up to the end of the original string. If beginIndex is equal to length in SubString(int beginIndex) it will return empty String.

SubString(), a method of String class is used to get a part of original string as String object. This method is defined in java.lang.String class.

This method has two types:

  1. SubString(int beginIndex):

This method returns part of String started from beginIndex up to the end of the original string. If beginIndex is equal to length in SubString(int beginIndex) it will return empty String.

  1. SubString(int beginIndex, int endIndex):

This method returns a new string starting from beginIndex to (one less than the second argument of the method) endIndex-1. If beginIndex is equal to endIndex then it will return empty String.

Example of SubString in Java:

import java.io.*;
import java.io.IOException;

public class FileReadExample {
public static void main(String args[]) throws IOException {
try{
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter file name");

String str = buff.readLine();
File file = new File(str);
FileInputStream fstream = new FileInputStream(file);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;

//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println(strLine);
String subString = str.substring(0);
System.out.println("String after index: " + subString); 
subString = str.substring(1,2);
System.out.println("Substring (1,2): " + subString);
}
//Close the input stream
in.close();
}
catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 24, 2013

Related Tutorials

Ask Questions?    Discuss: SubString in Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com