简体   繁体   中英

How to remove square brackets on either side of string value

When I choose a row on the table it prints out the selected item in a string as shown. How do I remove the square brackets from either side of the string.

Below is my code to populate TextFields with the data. You can see it populates successfully but with the [].

the table and output

表和输出

tableView.getSelectionModel().selectedItemProperty().addListener((v, oldValue, newValue) -> {
    String input = newValue.toString();
    String[] str_array = input.split(", ");
    String code = str_array[0]; 
    String name = str_array[1]; 
    String lecturer = str_array[2];
    String year = str_array[3];
    String semester = str_array[4];

    codeInput.setText(code);
    nameInput.setText(name);
    lectureInput.setText(lecturer);
    yearInput.setText(year);
    semesterInput.setText(semester);
    System.out.println(input);
});

You newValue should be an Object . Let's say it's an object of SchoolInfo with variables of String code , String name , String lecturer , int year , and int semester . Your Object should have Getters and Setters . You should do something like.

Warning: Some of those other answers may get the job done but are very bad ideas. The way you are trying to handle this data is a bad idea.

tableView.getSelectionModel().selectedItemProperty().addListener((v, oldValue, newValue) -> {
    SchoolInfo tempSchoolInfo = (SchoolInfo)newValue;

    String code = tempSchoolInfo.getCode(); 
    String name = tempSchoolInfo .getName(); 
    String lecturer = tempSchoolInfo.getLecturer;
    int year = tempSchoolInfo.getYear();
    int semester = tempSchoolInfo.getSemester();

    codeInput.setText(code);
    nameInput.setText(name);
    lectureInput.setText(lecturer);
    yearInput.setText(Integer.toString(year));
    semesterInput.setText(Integer.toString(semester));
    System.out.println(input);
});

您可以使用input.substr(1, input.length - 1)删除第一个和最后一个字符,或者如果没有input.replace("[","").replace("]","")可以使用input.replace("[","").replace("]","")删除它们其他情况也是可能的。

Arrays.stream(str_array).collect(Collectors.joining(","));

无需“后处理”即可产生所需的结果

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM