Home

Ask The Experts

The follow information is obtained from Yahoo! online community and does not express the views, opinions, or technical advice of On-Site. On-Site is not responsible for damages from use of information from Yahoo! Answers

Questioner's avatar
Cain
Counting characters after a character in a string in java.?
This is my code (which does not work btw): public class test { public static void main (String[] args) { Scanner scan = new Scanner (System.in); int DotPos, langd; String filtyp, text; System.out.println ("whatever: "); text = scan.nextLine(); DotPos = text.indexOf("."); langd = text.length(DotPos +1); System.out.println(langd); } } so what I want to do is seen by my " langd = text.length(DotPos +1); " code, but this does not work.. I'm thinking there must be a similar solution but I'm applying it wrong. Does anyone know? If you did not understand anything of the above this is what I'm trying to accomplish: I want to make a counter for how many characters there are after a character in a string, in this case the dot. I know I could do a loop count, but I'm wondering if there is a more simple solution than that? Thanks.
2 answer(s)

Best answer avatar
Best Answer:
// The source string
String text = "abc";

// The string to look for in the source string
String positionText = ".";

// Get the location of the search string
// (Keep in mind that a -1 will be returned if it
// doesn't exists)
int position = text.indexOf(positionText);

// This will hold the length of the characters after
// the search string. The whole length will return
// if the search string doesn't exist.
int length = 0;

// Need to check the position. -1 means no occurrence
// of the positionText value.
if (position > -1) {

// Remember that the position is based on a zero based
// array so need to add 1 to it for length
length = text.length() - position + 1;
} else {

// No search string so return the whole length
length = text.length();
}

View more answers to this question.