skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Thursday, October 4, 2012

Effective way for finding the number of occurences of a character or a special character in a String

Posted by Admin at 12:25 PM – 0 comments
 

In order to find the number of occurences of a character or a special character in a LENGTHY STRING or even a regular String,anyone can use this code which is very effective and very fast.
This reduces the manipulation of the Lengthy string for finding the number of occurences. 

public static int getNoOfOccurrences(String originalString,
   String characterToBeSearched, String strForSplit,
   String strForLastIndex) {

  int noOfOccurrences = 0;

  int lastIndex = originalString.lastIndexOf(strForLastIndex);

  int stringLength = originalString.length();

  if (stringLength == lastIndex + 1) {
   originalString = originalString + " ";
  }

  String strInArray[] = originalString.split(strForSplit);

  noOfOccurrences = strInArray.length - 1;

  return noOfOccurrences;
 }

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger