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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30587956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 09:51:40  来源:igfitidea点击:

How to split String before first comma?

javastringdelimiter

提问by Santosh Bhandary

I have an overriding method with String which returns String in format of:

我有一个 String 的覆盖方法,它以以下格式返回 String:

 "abc,cde,def,fgh"

I want to split the string content into two parts:

我想将字符串内容分成两部分:

  1. String before first comma and

  2. String after first comma

  1. 第一个逗号前的字符串和

  2. 第一个逗号后的字符串

My overriding method is :

我的首要方法是:

@Override
protected void onPostExecute(String addressText) {

    placeTitle.setText(addressText);
}

Now how do I split the string into two parts, so that I can use them to set the text in two different TextView?

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

采纳答案by Razib

You may use the following code snippet

您可以使用以下代码片段

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

回答by Saif

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`

If you want only cdeas the string after first comma. Then you can use

如果您只想cde作为第一个逗号后的字符串。然后你可以使用

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

or without the limit

或没有限制

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

Don't forget to check the lengthto avoid ArrayIndexOutOfBound.

不要忘记检查length以避免ArrayIndexOutOfBound.

回答by Arjit

 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()));

回答by Viraj Nalawade

The below is what you are searching for:

以下是您要搜索的内容:

public String[] split(",", 2)

This will give 2 string array. Split has two versions.What you can try is

这将给出 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

回答by almightyGOSU

// 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]);

For more information, refer to this documentation.

有关更多信息,请参阅此文档

回答by Rajesh

Use split with regex:

使用 split 与正则表达式:

String splitted[] = addressText.split(",",2);
System.out.println(splitted[0]);
System.out.println(splitted[1]);

回答by Yash

From jse1.4String- Two splitmethods are new. The subSequence method has been added, as required by the CharSequence interface that String now implements. Three additional methods have been added: matches, replaceAll, and replaceFirst.

来自-两种方法是新的。根据 String 现在实现的 CharSequence 接口的要求,添加了 subSequence 方法。另外三个方法已经被添加:,和jse1.4StringsplitmatchesreplaceAllreplaceFirst

Using Java String.split(String regex, int limit)with Pattern.quote(String s)

使用 JavaString.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" }

例如,字符串 "boo:and:foo" 使用这些参数产生以下结果:

  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 );
}

I have face the same problem in URL parameters, To resoleve it i need to split based on first ?So that the remaing String contains parameter values and they need to be split based on &.

我在 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 );
}


Run Javascript on the JVM with Rhino/Nashorn? With JavaScript's String.prototype.splitfunction:

使用 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", ""]

回答by Raju

:In this case you can use replaceAllwith some regex to get this input so you can use :

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

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

If the key is just an Stringyou can use (\\D?),.*

如果键只是一个字符串,你可以使用(\\D?),.*

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

回答by Brijesh Lakkad

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;
}

I created this function. Arguments are input string(String inp, here)and integer value(int n, here), which is the size of an array which contains values in string separated by commas. You can use other special character to extract values from string containing that character. This function will return array of integer of size n.

我创建了这个函数。参数是输入字符串(String inp, here)整数值(int n, here),它是包含以逗号分隔的字符串值的数组的大小。您可以使用其他特殊字符从包含该字符的字符串中提取值。此函数将返回大小为 n 的整数数组。

To use,

要使用

String inp1="444,55";
int values[]=stringToInt(inp1,2);