import java.net.*; import java.io.*; import java.util.*; /** * Provides one or two static methods to do with text * in a string. * * @author http://bumble.sf.net */ public class CountText extends Object { //-------------------------------------------- private static String NEWLINE = System.getProperty("line.separator"); //-------------------------------------------- private String text; //-------------------------------------------- public CountText() { this.text = ""; } //-------------------------------------------- public CountText(String sText) { this.text = sText; } //-------------------------------------------- /** count the number of times a particular character * appears in a piece of text */ public static int countOccurences(String sText, char cCheck) { char cCurrent; int iCount = 0; if (sText.indexOf(cCheck) == -1) { return 0; } for (int ii = 0; ii < sText.length(); ii++) { cCurrent = sText.charAt(ii); if (cCurrent == cCheck) { iCount++; } } //-- for return iCount; } //-- method: countOccurences //-------------------------------------------- /** a main method for testing */ public static void main(String[] args) throws Exception { StringBuffer sbUsageMessage = new StringBuffer(""); sbUsageMessage.append("test usage: java CountText text char"); sbUsageMessage.append(NEWLINE); StringBuffer sbMessage = new StringBuffer(""); if (args.length < 2) { System.out.println(sbUsageMessage); System.exit(-1); } //String sText = "abcdefghijklmnopqrst abcdefg 876543 "; String sText = args[0]; char cChar = args[1].charAt(0); System.out.print("Using text >"); System.out.println(sText); System.out.println(""); System.out.print(".countOccurences() >"); System.out.println(CountText.countOccurences(sText, cChar)); } //-- main() } //-- CountText class