【问题标题】:Comparing the elements of a list of strings比较字符串列表的元素
【发布时间】:2015-01-23 20:11:51
【问题描述】:

我正在尝试比较通过读取文件创建的列表的元素。

列表大小从 3 到 10 个元素不等。我想检查列表中的元素,比较它们的长度(我尝试通过String = s.length() 这样做)它有效,我得到了列表中每个元素的长度。

如何比较每个元素的长度?我想选择长度上最接近的 2 个元素并确定它们的索引。

例如,如果这是输入文件:

ATGTCATGG
ATGCGATGGGGGTCGCCC
ATGTTT

最近的 2 个字符串长度相差 3,它们的索引是 0 和 2。

public class ListTesting {
    public static void main(String[] args) throws IOException {
        PrintStream output = new PrintStream(System.out);
        Scanner input = new Scanner(System.in);
        output.print("Enter the name of the file ");
        String fileName = input.nextLine();
        Scanner fileInput = new Scanner(new File(fileName));
        List<String> listo = new ArrayList<String>();
        String token = "";
        while ( fileInput.hasNext() ) {
            token = fileInput.next();
            listo.add(token);
        }
        fileInput.close();
        for ( int i =0; i < listo.size(); i++) {
            String components = listo.get(i);
            int lengtho = components.length();
            //output.println(lengtho);  
        }   
    }
}

【问题讨论】:

  • 对不起,我第一次阅读时误解了你的问题:)
  • 如果您的实际目标是获得最接近的匹配字符串,您最好比较每对字符串的 Levenshtein 编辑距离。见en.wikipedia.org/wiki/Levenshtein_distance

标签: java string list if-statement linked-list


【解决方案1】:

如果可以更改行顺序,您可以创建一个Comparator 以按长度排序

public class LengthComparator implements Comparator<String> {
  public int compare(String s1, String s2) {
    return s1.length() - s2.length();
  }
}

使用 Collections.sort 按长度对列表进行排序,然后您可以遍历已排序的列表,将每个字符串与下一个字符串进行比较,看看是否比前一个最短的要短

int shortestIdx = 0;
int shortestDist = Math.abs(list.get(0).length() - list.get(1).length());
for (int idx = 0; idx < list.size(); idx++) {
  //left this for you to fill in
}

【讨论】:

  • 比较器实现 compare(T obj1,T obj2) 方法
  • @ControlAltDel 我试过这个但我得到一个错误.. int difference = 0; for (int i =0; i
  • 什么错误?如果你迷路了,你真的需要从你的老师那里得到更广泛的帮助,而不是 StackOverflow 的我们这里
【解决方案2】:

您可以使用Collections.sort(List&lt;T&gt; list, Comparator&lt;? super T&gt; c) 对列表进行排序,您可以在其中定义自己的比较器,以您的方式比较字符串。

【讨论】:

  • 然后你失去了索引:P
  • 对不起,OP问题实际上比我第一次阅读时要难一些。
  • 好的,将 sortList 保存为 tempList,然后从非排序列表 indexOf(Object o) :)))
猜你喜欢
  • 2017-02-02
  • 1970-01-01
  • 1970-01-01
  • 2021-10-17
  • 1970-01-01
  • 2012-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多