搜索拆分到不同列表位置的字符串并获取开始和结束位置

问题描述 投票:0回答:1

我有一个字符串被分成列表中的不同位置,例如,

List<String> str = new ArrayList<String>();
str.add("This is a ");
str.add("[{searched");
str.add("_placeholder}]");
str.add(" in this string.");

我想在列表中搜索“[{searched_string}]”,并想知道“[{searched_string}]”在列表中的起始位置和结束位置。例如,在上面的列表中,“[{searched_string}]”的起始位置分别是 1 和 2。

有人可以指导我使用任何可以返回正在搜索的字符串的开始和结束位置的算法吗?

java apache-poi openxml apache-poi-4
1个回答
0
投票

像下面的代码可以工作吗?它的效率不是很高,但似乎有效。对于问题中的列表,搜索字符串为

searched_placeholder
,它返回起始索引 1 和结束索引 2。

      List<String> str = new ArrayList<String>();
      str.add("This is a ");
      str.add("[{searched");
      str.add("_placeholder}]");
      str.add(" in this string.");
      
      String searchString = "searched_placeholder";
      StringBuilder completeString = new StringBuilder();
      int endIndex = 0;
      int startIndex = 0;
      
      for (int index = 0; index < str.size(); index++) {
          completeString.append(str.get(index));
          
          if (completeString.indexOf(searchString) != -1) {
              endIndex = index;
              break;
          }
      }
      
      for (int index = 0; index <= endIndex; index++) {
          completeString.replace(0, str.get(index).length(), "");
          
          if (completeString.indexOf(searchString) == -1) {
              startIndex = index;
              break;
          }
      }
      
      System.out.println("Start index: " + startIndex + ", End index: " + endIndex);
© www.soinside.com 2019 - 2024. All rights reserved.