Levi J Levi J - 3 months ago 7
Java Question

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

For example, I have the following string:

ABC123, CBA 123, cba.cba


How can I select just
ABC123
, emitting anything after the first comma?

For some reason, I have been able to get it to work the reverse way, but not the correct way. \_0.o_/

Here's some source code, even though it's not really relevant because it's not working:

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


This produces

CBA 123, cba.cba


SOLUTION

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

Answer

You can use StringBuilder to accomplish this pretty easily.

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