我如何 select 从第一个索引开始到第一个逗号的子字符串?

How can I select the substring beginning with the first index and up to the first comma?

例如,我有以下字符串:

ABC123, CBA 123, cba.cba

如何 select 仅 ABC123,在第一个逗号后发出任何内容?

出于某种原因,我已经能够让它以相反的方式工作,但不是正确的方式。 \_0.o_/

这是一些源代码,尽管它并不真正相关,因为它不起作用:

private void resultListValueChanged(javax.swing.event.ListSelectionEvent evt) {                                        
    // TODO add your handling code here:
    searchText.setText(resultList.getSelectedValue().substring(resultList.getSelectedValue().indexOf(",")+1).trim());    
}  

这会产生

CBA 123, cba.cba

解决方案

private void resultListValueChanged(javax.swing.event.ListSelectionEvent evt) {                                        
    // TODO add your handling code here:
    searchText.setText(resultList.getSelectedValue().substring(0,resultList.getSelectedValue().indexOf(",")));    
}  

您可以使用 StringBuilder 轻松完成此操作。

StringBuilder sb  = new StringBuilder(str);
String target = sb.substring(0,sb.indexOf(","));

我想你可以先拆分字符串:

String[] parts = string.split(",")

在你得到第一个之后

String word = parts[0]

indexOf 将为您提供指定子字符串“,”第一次出现的索引。 subString 将从头开始(零索引)到所需位置的字符串的一部分,在您的情况下是从 indexOf[=16 获得的索引=].请注意,EXCLUSIVE 中的结束索引表示直到该索引但不包括该索引。

String s = "ABC123, CBA 123, cba.cba";
System.out.println(s.substring(0, s.indexOf(",")));