我正在尝试用 java 编写一些小方法,但我无法弄明白。我想要做的是输入一个字符串,然后将一个 int 变量的值设置为数组中 this 的索引,即如果我有一个由
组成的数组[0] 'hi guys'
[1] 'this'
[2] 'is'
[3] 'sparta'
我的整数值设置为 0,我想找到第一次出现的“ta”,即 [3],所以我希望函数将我的整数设置为 3。
我现在所拥有的完全是错误的,有什么简单的方法可以做到这一点吗?我已经定义了一个名为 get() 的函数,它返回当前行的值(即本例中的 get(0) 将返回 'hi guys')。谁能帮帮我吗?
非常感谢:)
public void find(String line ) {
boolean found = false;
int i = cursor + 1;
while ( found = false && i!=cursor) {
if ((doc.get(cursor).indexOf( line ) > 0)){
cursor = i;
found = true;
}else {
cursor++;
cursor%=doc.size();
i++;
}
}
}
最佳答案
通常我不这样做,但今天是星期六,我很高兴,可能会喝醉
public void find(String line ) {
boolean found = false;
int i = 0;;
while (i < doc.size()) {
if ((doc.get(i).indexOf( line ) > 0)){
cursor = i;
found = true;
break;
}else {
i++;
}
}
if (found) {
// print cursor or do whatever
}
}
关于java - 在字符串数组中搜索子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5127756/