【问题标题】:Issues Splitting a String in Java在 Java 中拆分字符串的问题
【发布时间】:2020-11-17 00:35:01
【问题描述】:

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

  • 肯·克拉克
  • XL
  • 匹兹堡
  • 钢人
  • 病房 - 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);
}
}

【问题讨论】:

    标签: java string split delimiter


    【解决方案1】:

    我自己想通了,又回到使用数组。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-13
      • 2021-10-23
      • 1970-01-01
      相关资源
      最近更新 更多