在String数组中搜索子字符串?

时间:2011-02-26 15:28:26

标签: java arrays string search indexof

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

组成的数组
[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++;

   }
 }
 }

5 个答案:

答案 0 :(得分: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
   }
 }

答案 1 :(得分: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中找到它所在的位置。在这种情况下,您需要更复杂的解决方案。

示例:

答案 2 :(得分: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;
}

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

答案 3 :(得分: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;
                            }
                    }
            }
    }

答案 4 :(得分:0)

搜索实际的字符串[]而不是每一行是不是更明智?

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

相关问题