首页 > 解决方案 > 在 Java 中拆分字符串的问题

问题描述

我在按多个参数拆分字符串时遇到问题,我必须拆分的字符串由空格、逗号、数字符号和冒号组成。我正在尝试按每个参数拆分字符串,但只是遇到了在输出中多次打印内容的问题,因为我多次拆分字符串。我尝试使用数组,但这不起作用,因为它只是在寻找空格而不是其他参数。然后我想到了一个使用分隔符的想法,这种想法非常棒,直到我遇到一个错误,程序将继续无休止地运行并且不输出任何内容。所以我需要的帮助是能够以给定的格式分解字符串语句。这是输入:Clark, Ken, XL : Steelers,Pittsburgh : Ward#86这是我应该得到的输出:

到目前为止,这是我的代码:

public class NFL_Jersey_Order {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       
       Scanner scan = new Scanner(System.in); 
       System.out.println("Enter Order Information: ");
       //String name1 = scan.nextLine(); 
       scan.useDelimiter(",");
        
       String last = scan.next();
       String first = scan.next();
       first = first.trim();
        
       scan.useDelimiter(" ");
       String space1 = scan.next();
       String size = scan.next(); 
       //size = size.trim(); 
       
       scan.useDelimiter(" ");
       String space3 = scan.next(); 
       String space4 = scan.next(); 
       
       scan.useDelimiter(" ");
       String city = scan.next();
       
       scan.useDelimiter(" ");
       String space5 = scan.next(); 
       String player = scan.next(); 

 System.out.print(first + " " + last + "\n" + size + "\n" + space4 + "\n" + player);
}
}

标签: javastringsplitdelimiter

解决方案


设法自己弄清楚,回到使用数组。

public class Order_2 {

   
    public static void main(String[] args) {
        
      Scanner scan = new Scanner(System.in); 
      System.out.println("Enter Order Information: ");
      String name1 = scan.nextLine();
      
      String substrings[] = name1.split("[,:# ]"); 
      
      
      String team = substrings[7];
      substrings[7] = team.toUpperCase();
      
      
        
        System.out.println(substrings[2] + "\n" + substrings[0] + "\n" + substrings[4] + "\n" + substrings[8] + "\n" + substrings[7] + "\n" + substrings[11] + "-" + substrings[12]);
     
      
      
  
    }
}

推荐阅读