Java 创建一个与 java.lang.string class 中的 str.indexOf() 执行相同操作的方法
Java making a method that does the same thing as str.indexOf() from the java.lang.string class
作为练习,我正在尝试制作一个方法,该方法将一个字符串和一个字符作为用户输入,并查找该字符串是否包含该字符。如果有,它将 return 找到的索引,如果没有,它将 return -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;
}
如果您对它的工作原理有任何疑问,请提问,我很乐意回答。
作为练习,我正在尝试制作一个方法,该方法将一个字符串和一个字符作为用户输入,并查找该字符串是否包含该字符。如果有,它将 return 找到的索引,如果没有,它将 return -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;
}
如果您对它的工作原理有任何疑问,请提问,我很乐意回答。