Java从Java.lang.string类中创建了一个与str.indexOf()做同样事情的方法



作为一个练习,我试图制作一个方法,将字符串和字符作为用户输入,并查找该字符串是否包含字符。如果它这样做,它将返回找到的索引;如果没有,则返回-1。

我很困惑如何在不使用数组的情况下做到这一点,但我想做的是:

      StringIndexOfChar.indexOf(String str, char ch) {
       for (int i=0; i <= str.length(); i++) {
       str.charAt(i);
       if (ch == str.charAt(i)) {
       return i; }}
       return -1; }

它应该看起来像这样:

//method declarations need to declare the return type, name, and arguments
int indexOf(String s, char ch) {
 //loop over each index in the string
 for (int i = 0; i < s.length(); i++) {
  //if the char at this index is the one we are looking for
  if (ch == s.charAt(i)) {
   //return the index it was found it
   return i;
  }
 }
 //if we look at each char and do not find the one we want, return -1
 return -1;
}

如果你对它的工作原理有疑问,请问我,我很乐意回答。

最新更新