3

我正在尝试用java编写一个小方法,但我无法弄清楚。我想要做的是输入一个字符串,然后将 int 变量的值设置为数组中 this 的索引,即如果我有一个由以下组成的数组

[0] 'hi guys'
[1] 'this'
[2] 'is'
[3] 'sparta'

我的整数的值设置为 0,我想找到“ta”的第一次出现,这将是 [3],所以我希望函数将我的整数设置为 3。

我目前所拥有的完全是错误的,有没有简单的方法可以做到这一点?我已经定义了一个名为 get() 的函数,它返回当前行的值(即 get(0) 在这种情况下将返回“嗨,伙计们”)。谁能帮帮我?

非常感谢 :)

 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++;

   }
 }
 }
4

5 回答 5

2

通常我不这样做,但今天是星期六,我很高兴,可能会喝醉

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
   }
 }
于 2011-02-26T15:35:34.173 回答
2

你应该注意这是否是家庭作业。

一种方法是:

    int i = 0;
    String searchTerm = "ta";

    System.out.println("Following substrings contain search term:");
    for (String s : "hi guys,this,is,sparta".split(",")) {
        if (s.contains(searchTerm)) System.out.println(i++);
        else i++;
    }

或者,如果您更喜欢使用正则表达式,则s.contains(searchTerm)使用 s.matches(searchTerm).

如果这不是家庭作业,而是面试问题或工作问题,这将更加复杂。例如:氨基酸序列是搜索词,需要在DNA/RNA中找到它所在的位置。在这种情况下,您需要更复杂的解决方案。

例子:

于 2011-02-26T15:41:39.553 回答
1

如果正确理解您的任务,我会执行以下操作:

public int find(String line, int startPosition) {
    if (doc[startPosition].contains(line) {
        return startPosition;
    }
    for (int i = 0; i < Math.max(doc.size() - startPosition, startPosition); i++) {
        if (startPosition - i > 0 && doc[startPosition - i].contains(line)) {
            return startPosition - i;
        }
        if (startPosition + i < doc.size() && doc[startPosition + i].contains(line)) {
            return startPosition + i;
        }

    }
    return -1;
}

这将返回数组中包含作为行参数传递的子字符串的第一个元素的索引。

于 2011-02-26T15:36:29.690 回答
1

他说这不是家庭作业,所以这里是:

(这实际上编译和工作)

    import java.io.*;

    public class A {
            public static void main(String[] args) {
                    String[] arr = {"hi guys", "this", "is", "sparta"};
                    System.out.println("enter substring:");
                    String substr = "";
                    try {
                    substr = new BufferedReader(new InputStreamReader(System.in)).readLine();
                    } catch(IOException e) {System.exit(0);}
                    for(int i =0; i<arr.length; i++) {
                            int charPos = arr[i].indexOf(substr);
                            if(charPos!=-1) {
                                    System.out.println("found in string index " + i + " at "+charPos);
                                    break;
                            }
                    }
            }
    }
于 2011-02-26T15:47:03.293 回答
0

在实际的 string[] 中搜索而不是在每一行中搜索不是更明智吗?

然后遍历数组并返回当前索引,如果该位置的字符串包含子字符串。

于 2011-02-26T15:36:00.643 回答