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);
}
asked Nov 13, 2015 at 8:13
hades
4,77410 gold badges53 silver badges80 bronze badges
3 Answers 3
You can use
split = str1 .replaceAll("-", "','");
split = "'" + split + "'";
answered Nov 13, 2015 at 8:15
Eran
395k57 gold badges726 silver badges793 bronze badges
Sign up to request clarification or add additional context in comments.
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);
answered Nov 13, 2015 at 8:22
SomeJavaGuy
7,3872 gold badges24 silver badges33 bronze badges
2 Comments
hades
is there any solution for java 1.6? not using java 1.8
SomeJavaGuy
@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.
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));
}
answered Nov 13, 2015 at 8:35
TheLostMind
36.3k12 gold badges72 silver badges109 bronze badges
2 Comments
hades
is ur regex limited to only integer? my value might be: ***-100-TSK-534
TheLostMind
@user3172596 - You can replace
\\d+ with [a-zA-Z]+ if you have values like abc-asa etclang-java