Length of String in Java without using length() method - Java @ Desk

Friday, April 4, 2014

Length of String in Java without using length() method


Length of String in Java without using length() method

Length of the string can easily be obtained using String.length() easily but there are many more ways, although unconventional yet good ones to learn to get the length of the String.

1) Using String.lastIndexOf()
2) Using Reflection
3) Using char array
4) Using Regular Expression
5) Using StringBuffer
6) Using String.split()

package test;

import java.lang.reflect.Field;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LengthOfString {

 public static void main(String args[]) throws SecurityException,
   NoSuchFieldException, IllegalArgumentException,
   IllegalAccessException {
  String inputString = "This is the string";
  usingLength(inputString);
  usingIndexOf(inputString);
  usingReflection(inputString);
  usingCharArray(inputString);
  usingPatternMatcher(inputString);
  usingStringBuffer(inputString);
  usingSplit(inputString);
 }

 public static void usingLength(String inputString) {
  System.out.println("Length of String using length method - "
    + inputString.length());
 }

 public static void usingIndexOf(String inputString) {
  System.out.println("Length of String using indexOf method - "
    + inputString.lastIndexOf(""));
 }

 public static void usingReflection(String inputString)
   throws SecurityException, NoSuchFieldException,
   IllegalArgumentException, IllegalAccessException {
  Field count = String.class.getDeclaredField("count");
  count.setAccessible(true);
  System.out.println("Length of String using Reflection - "
    + count.getInt(inputString));
 }

 public static void usingCharArray(String inputString) {
  char charArray[] = inputString.toCharArray();
  int length = 0;
  for (char single : charArray) {
   length++;
  }
  System.out.println("Length of String using Char Array - " + length);
 }

 public static void usingPatternMatcher(String inputString) {
  Matcher matcher = Pattern.compile("$").matcher(inputString);
  matcher.find();
  int length = matcher.end();
  System.out
    .println("Length of String using Pattern Matcher - " + length);
 }

 public static void usingStringBuffer(String inputString) {
  System.out.println("Length of String using String Builder - "
    + new StringBuffer(inputString).length());
 }

 public static void usingSplit(String inputString) {
  System.out.println("Length of String using String Split - "
    + (inputString.split("").length - 1));
 }
}






No comments:

Post a Comment