17

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

 "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

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?

AndrewL64
  • 15,794
  • 8
  • 47
  • 79
Santosh Bhandary
  • 359
  • 2
  • 3
  • 19

9 Answers9

44

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());
Sandun Chathuranga
  • 2,242
  • 2
  • 13
  • 27
Razib
  • 10,965
  • 11
  • 53
  • 80
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`

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

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

or without the limit

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

Don't forget to check the length to avoid ArrayIndexOutOfBound.

Saif
  • 6,804
  • 8
  • 40
  • 61
  • 1
    splitted[1] will not return the full string after the first comma – Arjit Jun 02 '15 at 05:31
  • OP says :`2) string after first comma` what does it mean ? and if there is input like ` abc,cde,def,fgh` then i see `splitted[1] ` will return `cde` isn't it? @Arjit – Saif Jun 02 '15 at 05:33
  • 1
    No @saif you are wrong. _splitted[1]_ will have cde and Op wants to have _cde,def,fgh_ Also hope you read this in question **I want to split the string Content into two parts** – Viraj Nalawade Jun 02 '15 at 05:34
  • 1
    The method split(String) in the type String is not applicable for the arguments (char) – Rajesh Jun 02 '15 at 05:36
  • 2
    Probably it is a typo. String has not any overloaded version of `split()` method for `char`. Use s.split(",") instead. – Razib Jun 02 '15 at 05:37
3

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

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
Viraj Nalawade
  • 3,137
  • 3
  • 28
  • 44
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()));
Arjit
  • 3,290
  • 1
  • 17
  • 18
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]);

For more information, refer to this documentation.

almightyGOSU
  • 3,731
  • 6
  • 31
  • 41
1

Use split with regex:

String splitted[] = addressText.split(",",2);
System.out.println(splitted[0]);
System.out.println(splitted[1]);
Rajesh
  • 2,135
  • 1
  • 12
  • 14
0

From jse1.4String - Two split methods 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.

Using Java String.split(String regex, int limit) with 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 );
}

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 &.

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.split function:

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", ""]
Yash
  • 9,250
  • 2
  • 69
  • 74
0

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

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

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

System.out.println("test ::::"+test.replaceAll("(\\D?),.*", "$1"));
Raju
  • 459
  • 5
  • 23
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;
}

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.

To use,

String inp1="444,55";
int values[]=stringToInt(inp1,2);
Brijesh Lakkad
  • 611
  • 10
  • 13