# String Exercise

• 03-06-2009, 05:15 AM
carlodelmundo
String Exercise
Given a string, count the number of words ending in 'y' or 'z' -- so the 'y' in "heavy" and the 'z' in "fez" count, but not the 'y' in "yellow" (not case sensitive). We'll say that a y or z is at the end of a word if there is not an alphabetic letter immediately following it. (Note: Character.isLetter(char) tests if a char is an alphabetic letter.)

countYZ("fez day") → 2
countYZ("day fez") → 2
countYZ("day fyyyz") → 2

The problem says two loops. Here's my algorithm but I dont know how to implement it (im not so good with the character/string class):

Look for a space using indexOf(' '). Once you find the space, go back one index and see if it is a y or z... if it is.. raise the globalCount once.

Look at the end of the string using the .length() method. If the end of the string is y or z... add the global count.

Can anyone show me the light?
• 03-06-2009, 05:26 AM
Fubarable
your best bet is to give it a try first and try to implement the code yourself, then come back with this code if it doesn't work. Just throwing in the towel without first putting in some effort will guarantee that you'll never learn Java.
• 03-06-2009, 05:29 AM
carlodelmundo
Hi. I wanted to know if my logic is correct first before I coded. Is there a better algorithm than the one that I said?
• 03-06-2009, 05:47 AM
Fubarable
seriously man, the best test of your logic is to code it and run test sentences through it.
• 03-06-2009, 01:07 PM
jithan
class CountChars
{
public static void main(String arg[])
{
String str = "day fyyyz";
String sp[] = str.split(" ");
int count = 0;
for(int i=0;i<sp.length;i++)
{
if(sp[i].endsWith("z") || sp[i].endsWith("y"))
count++;
}
System.out.println(" Count chars ========= " + count);
}
}
• 03-06-2009, 01:59 PM
CJSLMAN
jithan... a couple of things... it's not a good idea to post complete code to OPs... too much temptation to cut & paste & forget. There's no learning process.
Another thing is that the code that you posted doesn't use the assignment specifications. You can get the OP in trouble ...

Luck,
CJSL