The following method returns the position of the first occurrence of a given character in a given string. The position starts from 0 for the first character in the string. The method should return -1 if the character does not appear in the string. For example, the call indexOf('t',"iteration") would return 1, and the call indexOf('s',"iteration") would return -1. (You are not allowed to use the String indexOf method.)
______________________________________...
public static int indexOf(char c, String str)
{
// fill this in
}
Any help will be very appreciative.
Java problem?
No need to reinvent the wheel, because there is a function in the String class that provides this functionality, but with a different function prototype. The function is index called indexOf() and is overloaded to accept most input. If you need this for some school assignment, then just "jack" the code from the String class.
Reply:public static int indexOf(char c, String str) {
char[] chars = str.toCharArray();
for(int i=0;i%26lt;chars.length;i++) {
if(c == chars[i]) {
return i;
}
}
return -1;
}
Reply:get the length of the string
use a loop to check each character in the string against 'c'
if you found some mathces, return the count
if not return -1
use the Character class
//fill it in on your own
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment