3

I have a string:

100-200-300-400

i want replace the dash to "," and add single quote so it become:

 '100','200','300','400'

My current code only able to replace "-" to "," ,How can i plus the single quote?

String str1 = "100-200-300-400";      
split = str1 .replaceAll("-", ",");

if (split.endsWith(",")) 
{
   split = split.substring(0, split.length()-1);
}

3 Answers 3

4

You can use

split = str1 .replaceAll("-", "','");
split = "'" + split + "'";
Sign up to request clarification or add additional context in comments.

2 Comments

that will only quote whole string into 1 single quote, '100,200,300,400'
@user3172596 I tested it and got '100','200','300','400'. The replaceAll call adds the remaining single quotes. Note that it's not the same replaceAll call as in your question.
1

As an alternative if you are using java 1.8 then you could create a StringJoiner and split the String by -. This would be a bit less time efficient, but it would be more safe if you take, for example, a traling - into account.

A small sample could look like this.

String string = "100-200-300-400-";
String[] splittet = string.split("-");
StringJoiner joiner = new StringJoiner("','", "'", "'");
for(String s : splittet) {
    joiner.add(s);
}
System.out.println(joiner);

2 Comments

is there any solution for java 1.6? not using java 1.8
@user3172596 it isn´t included inside the 1.6 jdk sadly. You´d need to go for regex otherwise. The solution provided by Eran should work.
0

This will work for you :

public static void main(String[] args) throws Exception {
    String s = "100-200-300-400";
    System.out.println(s.replaceAll("(\\d+)(-|$)", "'$1',").replaceAll(",$", ""));
}

O/P :

'100','200','300','400'

Or (if you don't want to use replaceAll() twice.

public static void main(String[] args) throws Exception {
    String s = "100-200-300-400";
    s = s.replaceAll("(\\d+)(-|$)", "'$1',");
    System.out.println(s.substring(0, s.length()-1));
}

2 Comments

is ur regex limited to only integer? my value might be: ***-100-TSK-534
@user3172596 - You can replace \\d+ with [a-zA-Z]+ if you have values like abc-asa etc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.