简体   繁体   English

如何在Java中使用/和空格分割字符串

[英]how to split a string using / and white space in java

My problem is I have a string like this 我的问题是我有这样的字符串

String text="UWU/CST/13/0032 F" 字符串text =“ UWU / CST / 13/0032 F”

I want this to split by / and white spaces and put into a array.So finally the array indexes should include following UWU, CST, 13, 0032, F 我想用/和空格分开并放入一个数组中,所以最后数组索引应该包括以下UWU,CST,13、0032,F

text.split("[/ ]")text.split("[/ ]", -1)如果要返回尾随的空标记。

Use the string.split(separator) method that takes a String (regex expression) as an argument. 使用将String(正则表达式)作为参数的string.split(separator)方法。 Here is the documentation. 这是文档。 http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String) http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)

If you have: 如果你有:

String text = "UWU/CST/13/0032 F";

You can separate it by the white space first, splitting it into an array of two Strings, and then split the first String in the array by "/". 您可以先用空格将其分隔,将其拆分为两个字符串的数组,然后用“ /”拆分数组中的第一个字符串。

    String text = "UWU/CST/13/0032 F";

    String[] array = text.split(" ");
    String[] other = array[0].split("/");

    for (String e : array) System.out.println(e);
    for (String e : other) System.out.println(e);

This code outputs: 此代码输出:

UWU/CST/13/0032
F
UWU
CST
13
0032

Regular expressions can be used in Java to split Strings using the String.split(String) method. Java中可以使用正则表达式使用String.split(String)方法拆分字符串。

For you particular situation, you should split the string on the regular expression "(\\s|/)" . 对于您的特殊情况,您应该在正则表达式"(\\s|/)"上拆分字符串。 \\s matches white space while / literally matches a forward slash. \\s匹配空格,而/匹配正斜杠。

The final code for this would be: 最终的代码是:

String[] splitString = text.split("(\\s|/)");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM