输入不会修剪

时间:2017-03-29 18:33:49

标签: java swing input joptionpane

全新的,但我不确定我做错了什么因为输出不会修剪。

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());
    }
}

2 个答案:

答案 0 :(得分:1)

删除领先和&尾随空格(使用trim()并替换String中的所有空格(使用replaceAll(" ", "")

示例输出

' Andrew,      52,  Sydney         '
'Andrew,      52,  Sydney'
'Andrew,52,Sydney'
  1. 原始字符串
  2. trim()
  3. replaceAll(" ", "")
  4. 代码

    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);
        }
    }
    

答案 1 :(得分:0)

trim()方法返回删除了前导和尾随空格的字符串副本,如果没有前导或尾随空格,则返回相同的字符串。

示例:

import java.io.*;
public class Test {

   public static void main(String args[]) {
      String Str = new String("   Some string with whitespace in front and after it.   ");

      System.out.print("Return Value :" );
      System.out.println(Str.trim() );
   }
}

输出:

Return Value :Some string with whitespace in front and after it.