java - 在 Java 中拆分字符串的问题
问题描述
我在按多个参数拆分字符串时遇到问题,我必须拆分的字符串由空格、逗号、数字符号和冒号组成。我正在尝试按每个参数拆分字符串,但只是遇到了在输出中多次打印内容的问题,因为我多次拆分字符串。我尝试使用数组,但这不起作用,因为它只是在寻找空格而不是其他参数。然后我想到了一个使用分隔符的想法,这种想法非常棒,直到我遇到一个错误,程序将继续无休止地运行并且不输出任何内容。所以我需要的帮助是能够以给定的格式分解字符串语句。这是输入:Clark, Ken, XL : Steelers,Pittsburgh : Ward#86这是我应该得到的输出:
- 肯克拉克
- 特大号
- 匹兹堡
- 钢人
- 病房 - 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);
}
}
解决方案
设法自己弄清楚,回到使用数组。
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]);
}
}
推荐阅读
- android-jetpack-compose - 无法在 jetpack compose 桌面中显示图标
- sql - 识别模式以获得所需的输出
- python - 如何修复生产中的 502 Bad Gateway Error(Nginx)?
- spring - 将 RestTemplate ResponseEntity 对象映射到域对象的位置
- javascript - D3.JS 条形图圆角
- javascript - 如何使 JavaScript 单元格占据整个行宽
- wordpress - .htaccess 中的 301 重定向错误?WP网站
- youtube - 在不同设备上使用相同谷歌客户端的 Youtube 数据 API 配额
- ruby-on-rails - 此模型适配器不支持从数据库中获取记录
- php - 如何对字符串和变量都使用explode?