Similar to this I also need to count how many times a specific character occurs in a String. Do I just need to remove the while statement or is there more to it?
/********************
* Searches thtrough the string, locates the nth term of the character c. and returns
* the index of that character, using a while loop that starts at the beginning of the
* String and scans forward.
********************/
int findNthChar(String a, char c, int n)
{
int w = 0; //intial value for while loop
int idx = -1; //initial index value
while (w++ < n)
{
if ((idx = a.indexOf(c, idx+1)) < 0)
{
return -1;
}
}
return idx;
}
and the stringFront():
/********************
* Returns the first count characters of the String as a new String.
********************/
String stringFront(String s, int count)
{
String ss = s.substring(0,count);
return ss;
}
to create the getFirstWords():
/********************
* Returns a new String containing the first n words in s, where the character delimiter
* defines a word boundary, using stringFront to get the actual words as a new String.
********************/
String getFirstWords(String s, int n, char delimiter)
{
String firstWord = stringFront(s, findNthChar(s, delimiter, n));
return firstWord;
}
Answers
Similar to this I also need to count how many times a specific character occurs in a String. Do I just need to remove the while statement or is there more to it?
I now have to utilize the findNthChar():
and the stringFront():
to create the getFirstWords():
Am I close with getFirstWords()?
I don't think so.
words is plural