Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim or replace all commas and spaces from the String

Tags:

java

android

Hi i am developing android application.Now i stuck in one problem. Let me give you a example to understand my problem.

What I have is : kushal,mayurv,narendra,dhrumil,mark, ,,,, ,

What i want is : kushal,mayurv,narendra,dhrumil,mark

Any help is appreciated.

like image 614
Kushal Shah Avatar asked Dec 03 '22 05:12

Kushal Shah


2 Answers

Try with the following code to trim all unwanted comma and whitespaces

String str = "kushal,mayurv,narendra,dhrumil,mark, ,,,, ";
        String splitted[] = str.split(",");
        StringBuffer sb = new StringBuffer();
        String retrieveData = "";
        for(int i =0; i<splitted.length; i++){
            retrieveData = splitted[i];
            if((retrieveData.trim()).length()>0){

                if(i!=0){
                    sb.append(",");
                }
                sb.append(retrieveData);

            }
        }

    str = sb.toString();
    System.out.println(str);
like image 195
Sunil Kumar Sahoo Avatar answered Dec 15 '22 06:12

Sunil Kumar Sahoo


Use regex to solve it. You want to remove all (,) that are followed by space or another (,). You also want to remove all (,) that isn't followed by a letter.

Regex in Android

yourstring = yourstring.replaceAll("( ,)|(,,)", ""); 

Something like that, sorry that I can't help you more.

like image 32
auo Avatar answered Dec 15 '22 06:12

auo