在Android Studio中获取数组中两个字符串之间的所有字符串

问题描述 投票:-1回答:2

我正在寻找一种方法来获取数组中两个字符串之间的所有字符串。

String [] list = inputOCR.split(“(?= \ p {Space})”); =这就是我构建数组的方式。

字符串的顺序类似于[其他,名称,中间,第一,最后,地址,单词,单词,单词,单词,单词,单词,许可证等,等等,等等,等等]如何获得数组中地址和许可证之间的所有单词?

更新:数组的索引不是基于OCR扫描而固定的,所以我还必须在数组中查找单词“ Address”和“ License”。

java android arrays
2个回答
1
投票

啊,是的,索引可能会造成混淆!我有一些代码可能会帮助您。将单词拆分为数组后,您想要做的就是找到单词的索引(位置),它们是搜索的起点和终点。在这种情况下,为“地址”和“许可证”。然后,您可以在这些值之间循环以获取所需的单词。

public class GetWords {

public static void main(String[] args) {
    String inputOCR = "This contains some address random words used to test License should not be picked up";
    String[] list = inputOCR.split(" "); 

    int startPosition = getIndexOfWordInArray(list, "address") + 1;
    int endPosition = getIndexOfWordInArray(list, "license");

    for (int i = startPosition; i < endPosition; i++) {
        System.out.println(list[i]);
    }
}

public static int getIndexOfWordInArray(String[] list, String word) {
    int index = -1;

    for (int i = 0; i < list.length; i++) {
        if (list[i].equalsIgnoreCase(word)) {
            index = i;
            break;
        }
    }

    return index;
}
}

上面的代码将字符串分割为空格,然后从索引中获取“地址”和“许可证”的位置。然后,它遍历数组,在这两个位置之间打印单词。该代码在“地址”的位置加1,因为您要排除它,并且它在“许可证”的位置之前停止。

代替打印单词,您可以将它们添加到ArrayList中,ArrayList是一个可以动态增长的数组,具体取决于您输入的数量。

我试图使代码尽可能简单和便于初学者使用,但是请问是否仍然不清楚。


0
投票

好吧,如果我说对了,我希望我做到了,这应该可以解决问题:

// Code begins with a splitted array so String[] list exists already
int address = 0; // this will determine where your Address is located in the array
int license = -1; // this will determine where license is located in the array

for (int i = 0; i < list.length; i++) {
    if (list[i].equals("Address"))
        address = i;
    else if (address != 0 && list[i].equals("License")) {
        license = i;
        break;    // loop can be left as everything else is unimportant
    }
}

String[] result = new String[license-address-1];. // This will throw an error on purpose if license and/or address were not in list
for (int i = address+1; i < license; i++)
    result[i-address-1] = list[i]; // actual copying
// Be happy with your result String[]
© www.soinside.com 2019 - 2024. All rights reserved.