Monday, December 9, 2013

Find the String length without using the String API of Java

                                   Generally, String is collection of Characters.String are immutable objects in Java. String is playing vital role in Java programming language. Java main() method parameter is also String array and Java is taking defaultly String. If we want to know the length of the String in java by using String API method length().But my question is how to find the length of the String without using String API of Java. Is it possible to find the String length without String API? Yes,it is possible to find String length without String API.

                                  By using File concept we can find the length of the String. By storing the each character of the String into the file and parallelly counting the characters. See the below example

package com.rrvtechdiamond;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class LengthOfString {

public static void main(String[] args) throws IOException {

          String nameOfBlog = "RRV TECH DIAMOND";
          
 File file = new File("G:/rrvtechdiamond.txt");//creating file object
 
 file.createNewFile();// creating file 
 
 
 FileWriter fileWriter = new FileWriter(file);
 
 fileWriter.write(nameOfBlog);//By using the write method write String to file
 
 fileWriter.close();//close the file
 
 FileReader fileReader = new FileReader(file);//create FileReader object
          
 int characterValue = 0, count = 0;
 
 while((characterValue = fileReader.read()) != -1){
 count++;
 }
 fileReader.close();//close fileReader
 
 System.out.println("length of the String is: "+count);
 
 
}

Output :

length of the String is: 16

No comments:

Post a Comment