如何在第一个逗号之前拆分字符串?

17

我有一个带有String的覆盖方法,返回格式为String:

 "abc,cde,def,fgh"

我想把字符串内容分成两部分:
  1. 第一个逗号之前的字符串
  2. 第一个逗号之后的字符串
我的重写方法是:
@Override
protected void onPostExecute(String addressText) {

    placeTitle.setText(addressText);
}

我该如何将字符串分成两部分,以便我可以使用它们来设置两个不同的 TextView 的文本?

9个回答

44

你可以使用以下代码片段

String str ="abc,cde,def,fgh";
String kept = str.substring( 0, str.indexOf(","));
String remainder = str.substring(str.indexOf(",")+1, str.length());

1
我认为这是最好的答案,因为你可以在一行中完成。谢谢。 - Shadrack Kimutai
1
但如果它找不到任何逗号,则会崩溃并显示错误 -----java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-1 - Aditya Patil

11
String splitted[] =s.split(",",2); // will be matched 1 times. 

splitted[0]  //before the first comma. `abc`
splitted[1]  //the whole String after the first comma. `cde,def,fgh`
如果你想让第一个逗号后面只保留字符串cde,那么你可以使用

String splitted[] =s.split(",",3); // will be matched  2 times

或者没有限制

String splitted[] =s.split(",");

别忘了检查length避免ArrayIndexOutOfBound


1
splitted[1] 不会返回第一个逗号后的完整字符串。 - Arjit
OP说:“2)第一个逗号后的字符串是什么意思?”如果输入为“abc,cde,def,fgh”,那么我看到splitted[1]将返回cde,不是吗?@Arjit - Saif
1
不对,@saif。splitted[1] 将会是 cde,而 Op 想要的是 _cde,def,fgh_。另外希望你在问题中看到这一点:我想将字符串 Content 分成两部分 - Viraj Nalawade
1
类型String中的split(String)方法不适用于参数(char)。 - Rajesh
2
еҸҜиғҪжҳҜжү“й”ҷдәҶгҖӮStringжІЎжңүд»»дҪ•й’ҲеҜ№charзҡ„split()ж–№жі•зҡ„йҮҚиҪҪзүҲжң¬гҖӮиҜ·дҪҝз”Ёs.split(",")д»ЈжӣҝгҖӮ - Razib

3
以下是您正在搜索的内容:
public String[] split(",", 2)

这将给出2个字符串数组。Split有两个版本。你可以尝试的是:
String str = "abc,def,ghi,jkl";
String [] twoStringArray= str.split(",", 2); //the main line
System.out.println("String befor comma = "+twoStringArray[0]);//abc
System.out.println("String after comma = "+twoStringArray[1]);//def,ghi,jkl

2
 String s =" abc,cde,def,fgh";
 System.out.println("subString1="+ s.substring(0, s.indexOf(",")));
 System.out.println("subString2="+ s.substring(s.indexOf(",") + 1, s.length()));

1
// Note the use of limit to prevent it from splitting into more than 2 parts
String [] parts = s.split(",", 2);

// ...setText(parts[0]);
// ...setText(parts[1]);

更多信息,请参考文档


1
使用正则表达式的split方法:
String splitted[] = addressText.split(",",2);
System.out.println(splitted[0]);
System.out.println(splitted[1]);

0

jse1.4String - 新增了两个split方法。由于现在实现了CharSequence接口,因此添加了subSequence方法。另外还添加了三个方法:matchesreplaceAllreplaceFirst

使用Java String.split(String regex, int limit)Pattern.quote(String s)

The string "boo:and:foo", for example, yields the following results with these parameters:

  Regex     Limit          Result
    :         2       { "boo", "and:foo" }
    :         5       { "boo", "and", "foo" }
    :        -2       { "boo", "and", "foo" }
    o         5       { "b", "", ":and:f", "", "" }
    o        -2       { "b", "", ":and:f", "", "" }
    o         0       { "b", "", ":and:f" }
String str = "abc?def,ghi?jkl,mno,pqr?stu,vwx?yz";
String quotedText = Pattern.quote( "?" );
// ? - \\? we have to escape sequence of some characters, to avoid use Pattern.quote( "?" );
String[] split = str.split(quotedText, 2); // ["abc", "def,ghi?jkl,mno,pqr?stu,vwx?yz"]
for (String string : split) {
    System.out.println( string );
}

我在URL参数方面遇到了同样的问题,为了解决它,我需要根据第一个?进行分割,这样剩余的字符串就包含了参数值,它们需要根据&进行分割。

String paramUrl = "https://www.google.co.in/search?q=encode+url&oq=encode+url";

String subURL = URLEncoder.encode( paramUrl, "UTF-8");
String myMainUrl = "http://example.com/index.html?url=" + subURL +"&name=chrome&version=56";

System.out.println("Main URL : "+ myMainUrl );

String decodeMainURL = URLDecoder.decode(myMainUrl, "UTF-8");
System.out.println("Main URL : "+ decodeMainURL );

String[] split = decodeMainURL.split(Pattern.quote( "?" ), 2);

String[] Parameters = split[1].split("&");
for (String param : Parameters) {
    System.out.println( param );
}

使用Rhino / Nashorn在JVM上运行JavaScript « 使用JavaScript的String.prototype.split函数:

var str = "abc?def,ghi?jkl,mno,pqr?stu,vwx?yz";
var parts = str.split(',');
console.log( parts ); // (5) ["abc?def", "ghi?jkl", "mno", "pqr?stu", "vwx?yz"]
console.log( str.split('?') ); // (5) ["abc", "def,ghi", "jkl,mno,pqr", "stu,vwx", "yz"]

var twoparts = str.split(/,(.+)/);
console.log( parts ); // (3) ["abc?def", "ghi?jkl,mno,pqr?stu,vwx?yz", ""]
console.log( str.split(/\?(.+)/) ); // (3) ["abc", "def,ghi?jkl,mno,pqr?stu,vwx?yz", ""]

0
public static int[] **stringToInt**(String inp,int n)
{
**int a[]=new int[n];**
int i=0;
for(i=0;i<n;i++)
{
    if(inp.indexOf(",")==-1)
    {
        a[i]=Integer.parseInt(inp);
        break;
    }
    else
    {
        a[i]=Integer.parseInt(inp.substring(0, inp.indexOf(",")));
        inp=inp.substring(inp.indexOf(",")+1,inp.length());
    }
}
return a;
}

我创建了这个函数。参数是输入字符串(此处为String inp)整数值(int n, 此处),它是包含以逗号分隔的字符串值的数组的大小。您可以使用其他特殊字符从包含该字符的字符串中提取值。此函数将返回大小为n的整数数组。 使用方法:
String inp1="444,55";
int values[]=stringToInt(inp1,2);

0

在这种情况下,您可以使用replaceAll和一些正则表达式来获取此输入,以便您可以使用:

 System.out.println("test another :::"+test.replaceAll("(\\.*?),.*", "$1"));

如果键只是一个字符串,您可以使用(\\D?),.*
System.out.println("test ::::"+test.replaceAll("(\\D?),.*", "$1"));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接