我想通过分隔符“-”将字符串“004-034556”拆分为两个字符串:
part1 = "004";
part2 = "034556";
这意味着第一个字符串将包含“-”之前的字符,第二个字符串将包括“-”之后的字符。
我还想检查字符串中是否有“-”。
我想通过分隔符“-”将字符串“004-034556”拆分为两个字符串:
part1 = "004";
part2 = "034556";
这意味着第一个字符串将包含“-”之前的字符,第二个字符串将包括“-”之后的字符。
我还想检查字符串中是否有“-”。
当前回答
根据文档:
public String[]split(Stringregex,int limit)围绕给定正则表达式的匹配项拆分此字符串。此方法返回的数组包含此字符串的子字符串,该子字符串由另一个与给定表达式匹配或以一串数组中的子字符串的顺序如下出现在此字符串中。如果表达式与输入,则结果数组只有一个元素,即一串
基本上你可以这样做:
String s = "123-456-789-123"; // The String to be split
String[] array = s.split("-"); // Split according to the hyphen and put them in an array
for(String subString : array){ // Cycle through the array
System.out.println(subString);
}
输出:
123
456
789
123
其他回答
直接处理字符串的另一种方法是将正则表达式与捕获组一起使用。这样做的优点是,它可以直接暗示对输入的更复杂的约束。例如,以下命令将字符串拆分为两部分,并确保两者仅由数字组成:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class SplitExample
{
private static Pattern twopart = Pattern.compile("(\\d+)-(\\d+)");
public static void checkString(String s)
{
Matcher m = twopart.matcher(s);
if (m.matches()) {
System.out.println(s + " matches; first part is " + m.group(1) +
", second part is " + m.group(2) + ".");
} else {
System.out.println(s + " does not match.");
}
}
public static void main(String[] args) {
checkString("123-4567");
checkString("foo-bar");
checkString("123-");
checkString("-4567");
checkString("123-4567-890");
}
}
由于模式在本例中是固定的,因此可以预先编译并存储为静态成员(在示例中是在类加载时初始化的)。正则表达式为:
(\d+)-(\d+)
括号表示捕获组;可以通过Match.group()方法访问与正则表达式的该部分匹配的字符串,如图所示。\d匹配一个十进制数字,+表示“匹配一个或多个前一个表达式)。-没有特殊含义,因此只匹配输入中的字符。请注意,当将其写成Java字符串时,需要对反斜杠进行双转义。其他一些示例:
([A-Z]+)-([A-Z]+) // Each part consists of only capital letters
([^-]+)-([^-]+) // Each part consists of characters other than -
([A-Z]{2})-(\d+) // The first part is exactly two capital letters,
// the second consists of digits
要拆分字符串,请使用string.split(regex)。查看以下示例:
String data = "004-034556";
String[] output = data.split("-");
System.out.println(output[0]);
System.out.println(output[1]);
输出
004
034556
注:
此拆分(正则表达式)以正则表达式作为参数。记住转义正则表达式特殊字符,如句点/点。
我只是想写一个算法,而不是使用Java内置函数:
public static List<String> split(String str, char c){
List<String> list = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++){
if(str.charAt(i) != c){
sb.append(str.charAt(i));
}
else{
if(sb.length() > 0){
list.add(sb.toString());
sb = new StringBuilder();
}
}
}
if(sb.length() >0){
list.add(sb.toString());
}
return list;
}
有时,如果您想拆分包含+的字符串,那么它不会拆分;相反,您将得到一个运行时错误。在这种情况下,首先将+替换为_,然后拆分:
this.text=text.replace("/", "_");
String temp[]=text.split("_");
我查看了所有答案,发现所有答案都是第三方许可或基于正则表达式的。
下面是我使用的一个很好的哑实现:
/**
* Separates a string into pieces using
* case-sensitive-non-regex-char-separators.
* <p>
* <code>separate("12-34", '-') = "12", "34"</code><br>
* <code>separate("a-b-", '-') = "a", "b", ""</code>
* <p>
* When the separator is the first character in the string, the first result is
* an empty string. When the separator is the last character in the string the
* last element will be an empty string. One separator after another in the
* string will create an empty.
* <p>
* If no separators are set the source is returned.
* <p>
* This method is very fast, but it does not focus on memory-efficiency. The memory
* consumption is approximately double the size of the string. This method is
* thread-safe but not synchronized.
*
* @param source The string to split, never <code>null</code>.
* @param separator The character to use as splitting.
* @return The mutable array of pieces.
* @throws NullPointerException When the source or separators are <code>null</code>.
*/
public final static String[] separate(String source, char... separator) throws NullPointerException {
String[] resultArray = {};
boolean multiSeparators = separator.length > 1;
if (!multiSeparators) {
if (separator.length == 0) {
return new String[] { source };
}
}
int charIndex = source.length();
int lastSeparator = source.length();
while (charIndex-- > -1) {
if (charIndex < 0 || (multiSeparators ? Arrays.binarySearch(separator, source.charAt(charIndex)) >= 0 : source.charAt(charIndex) == separator[0])) {
String piece = source.substring(charIndex + 1, lastSeparator);
lastSeparator = charIndex;
String[] tmp = new String[resultArray.length + 1];
System.arraycopy(resultArray, 0, tmp, 1, resultArray.length);
tmp[0] = piece;
resultArray = tmp;
}
}
return resultArray;
}