I want to split and get rid of the comma's in a string like this that are entered into a textfield:
1,2,3,4,5,6
and then display them in a different textfield like this:
123456
here is what i have tried.
String text = j开发者_运维知识库TextField1.getText();
String[] tokens = text.split(",");
jTextField3.setText(tokens.toString());
Can't you simply replace the ,
?
text = text.replace(",", "");
If you're going to put it back together again, you don't need to split it at all. Just replace the commas with the empty string:
jTextField3.setText(text.replace(",", ""));
Assuming this is what you really want to do (e.g. you need to use the individual elements somewhere before concatenating them) the following snippet should work:
String s1 = "1,2,3,4,5,6";
String ss[] = s1.split(",", 0);
StringBuilder sb = new StringBuilder();
for (String s : ss) {
// Use each element here...
sb.append(s);
}
String s2 = sb.toString(); // 123456
Note that the String#split(String) method in Java has strange default behavior so using the method that takes an additional int parameter is recommended.
I may be wrong, but I believe that call to split will get rid of the commas. And it should leave tokens an array of just the numbers
精彩评论