Brand new to this but I'm not sure what I am doing wrong as the output will not trim.
package cs520.hw3.part1;
import javax.swing.JOptionPane;
public class StringTest {
public static void main(String[] args) {
String input = JOptionPane.showInputDialog("Enter data using the format Name, Age, City");
//String delimiter = ",";
//String[] tokens = input.split(delimiter);
System.out.println(input.trim());
}
}
There is a difference between removing the leading & trailing spaces (using trim()
and replacing all spaces from a String
(using replaceAll(" ", "")
)
' Andrew, 52, Sydney '
'Andrew, 52, Sydney'
'Andrew,52,Sydney'
trim()
replaceAll(" ", "")
import javax.swing.*;
public class TrimSpace {
TrimSpace() {
String s = JOptionPane.showInputDialog(null,
"Name, Age, City",
"Person Details",
JOptionPane.QUESTION_MESSAGE);
// show the raw string entered by user
System.out.println(String.format("'%1s'", s));
// remove leading & trailing space from string
System.out.println(String.format("'%1s'", s.trim()));
// remove all spaces from string
System.out.println(String.format("'%1s'", s.replaceAll(" ", "")));
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
new TrimSpace();
}
};
SwingUtilities.invokeLater(r);
}
}