markus
markus

Reputation: 6588

remove substring followed by a comma in java

I want to remove numbers separated by a comma in a string:

String s= "1000, 2000, 3000, 4000, 1000";
s= s.replace("1000","");
System.out.println(s);

The result is:

", 2000, 3000, 4000,"

I want to cut also leading and tailing commas, so the expected result is:

"2000, 3000, 4000"

How can I do this?

Upvotes: 1

Views: 1487

Answers (3)

Yogesh Suthar
Yogesh Suthar

Reputation: 30488

This question is related with Java, but if anyone want to achieve same in Javascript then its solution is

Code

var s = "1000, 2000, 3000, 1000, 4000, 11000, 1000";
s = s.replace(/(1000, |, 1000)/g, "");
alert(s);

Output

2000, 3000, 4000, 11000

Live Demo

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533920

I would use

String s = "1000, 2000, 3000, 4000, 11000, 1000";
s = s.replaceAll("\b(1000, |, 1000)\b", "");
System.out.println(s);

prints

2000, 3000, 4000, 11000

Or I would use a proper List

List<Integer> ints = new ArrayList<Integer>(Arrays.asList(
                         1000, 2000, 3000, 4000, 1000, -1000, 11000 ));
while(ints.remove((Integer) 1000));
System.out.println(ints);

prints

[2000, 3000, 4000, -1000, 11000]

If you really have to use String, you can do

String s = "1000, 2000, 3000, 4000, 1000, -1000, 11000";
List<String> ints = new ArrayList<String>(Arrays.asList(s.split(", ")));
while (ints.remove("1000")) ;
System.out.println(ints);

prints

[2000, 3000, 4000, -1000, 11000]

Upvotes: 4

perilbrain
perilbrain

Reputation: 8207

String s= "1000, 2000, 3000, 4000, 1000";
s= s.replace("1000","");
String[] spl=s.split(',');
String result="";
for(int i=0;i<spl.length;i++)
{ 
  if(spl[i].length()>1)//for space
   result+=spl[i]+",";      
}
result=result.substring(0,result.length()-2);
System.out.println(result);

Upvotes: 1

Related Questions