简体   繁体   English

如何删除字符串值两边的方括号

[英]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. 以下是我的数据填充TextFields的代码。 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 . newValue应该是一个Object Let's say it's an object of SchoolInfo with variables of String code , String name , String lecturer , int year , and int semester . 假设它是SchoolInfo的对象,具有String codeString nameString lecturerint yearint semester变量。 Your Object should have Getters and Setters . 您的Object应该具有GettersSetters 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(","));

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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