我想通过分隔符“-”将字符串“004-034556”拆分为两个字符串:

part1 = "004";
part2 = "034556";

这意味着第一个字符串将包含“-”之前的字符,第二个字符串将包括“-”之后的字符。

我还想检查字符串中是否有“-”。


当前回答

我使用了一个名为stringValue的字符串,它的形式类似于“那些有硬币的人,在雨中享受,那些有钞票的人正忙着寻找避难所”。

我将使用“,”作为冒号拆分stringValue。

然后,我只想使用三个不同TextView的SetText()来显示该字符串。

String stringValue = "Those who had coins, enjoyed in the rain, those who had notes were busy looking for the shelter";
String ValueSplitByColon[] = stringValue.split(",");

String firstValue = ValueSplitByColon[0];
String secondValue = ValueSplitByColon[1];
String thirdValue = ValueSplitByColon[2];

txtV1.setText(firstValue);
txtV2.setText(secondValue;
txtV3.setText(thirdValue;

其输出如下:

txtV1值是:那些有硬币的人txtV2值为:在雨中享受txtV3值是:那些有笔记的人正忙着寻找避难所

其他回答

String s="004-034556";
for(int i=0;i<s.length();i++)
{
    if(s.charAt(i)=='-')
    {
        System.out.println(s.substring(0,i));
        System.out.println(s.substring(i+1));
    }
}

正如大家所提到的,split()是在您的案例中可能使用的最佳选项。另一种方法可以是使用substring()。

对于简单的用例,String.split()应该完成这项工作。如果您使用番石榴,还有一个Splitter类,它允许链接不同的字符串操作并支持CharMatcher:

Splitter.on('-')
       .trimResults()
       .omitEmptyStrings()
       .split(string);

使用Regex使用多个字符拆分字符串

public class StringSplitTest {
     public static void main(String args[]) {
        String s = " ;String; String; String; String, String; String;;String;String; String; String; ;String;String;String;String";
        //String[] strs = s.split("[,\\s\\;]");
        String[] strs = s.split("[,\\;]");
        System.out.println("Substrings length:"+strs.length);
        for (int i=0; i < strs.length; i++) {
            System.out.println("Str["+i+"]:"+strs[i]);
        }
     }
  }

输出:

Substrings length:17
Str[0]:
Str[1]:String
Str[2]: String
Str[3]: String
Str[4]: String
Str[5]: String
Str[6]: String
Str[7]:
Str[8]:String
Str[9]:String
Str[10]: String
Str[11]: String
Str[12]:
Str[13]:String
Str[14]:String
Str[15]:String
Str[16]:String

但不要期望所有JDK版本都有相同的输出。我看到了一个bug,在某些JDK版本中,第一个空字符串被忽略了。此错误在最新的JDK版本中不存在,但在JDK1.7晚期版本和1.8早期版本之间的某些版本中存在。

实现这一点的一种方法是在for每个循环中运行字符串,并使用所需的拆分字符。

public class StringSplitTest {

    public static void main(String[] arg){
        String str = "004-034556";
        String split[] = str.split("-");
        System.out.println("The split parts of the String are");
        for(String s:split)
        System.out.println(s);
    }
}

输出:

The split parts of the String are:
004
034556

直接处理字符串的另一种方法是将正则表达式与捕获组一起使用。这样做的优点是,它可以直接暗示对输入的更复杂的约束。例如,以下命令将字符串拆分为两部分,并确保两者仅由数字组成:

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