Reputation:
I need a function to put a hyphen where letters finish and numbers start or when numbers finish and letters start, for example, 1234GRR
to 1234-GRR
.
I am using Java 6.
I have this, but this just puts a hyphen everwhere.
public static String addHyphen(String word) {
StringBuilder longer = new StringBuilder(word.substring(0,1));
for (int i = 1; i < word.length(); i++) {
longer.append("-" + word.charAt(i));
}
return longer.toString();
}
Can anyone help me? Thanks!
Upvotes: 0
Views: 646
Reputation: 79435
You can do it using regex arguments as shown below:
public class Main {
public static void main(String[] args) {
// Test
String[] testStrs = { "1234GRR", "GRR1234", "Hello", "Hello1234World", "1234GRR1234GRR" };
for (String s : testStrs) {
System.out.println(addHyphen(s));
}
}
public static String addHyphen(String word) {
String str = null;
if (word != null) {
str = word.replaceAll("([0-9]+)([A-Za-z]+)", "$1-$2");
str = str.replaceAll("([A-Za-z]+)([0-9]+)", "$1-$2");
}
return str;
}
}
Output:
1234-GRR
GRR-1234
Hello
Hello-1234-World
1234-GRR-1234-GRR
Note: $1
and $2
refer to the first and second capturing group respectively.
Upvotes: 0
Reputation: 96
Try this:
public static String addHyphen(String word) {
boolean words=false;
boolean number=false;
String end=new String();
for (int i = 0; i < word.length(); i++) {
if (word.substring(i,i+1).matches("[1-9+]")&number==false){
number=true;
words=false;
end=end+"-"+word.substring(i,i+1);
}else if (word.substring(i,i+1).matches("[a-zA-Z]")&words==false){
number=false;
words=true;
end=end+"-"+word.substring(i,i+1);
}else {
end=end+word.substring(i,i+1);
}
}
return end.substring(1);
}
Upvotes: 1
Reputation: 159165
The simplest solution would be to use a regex, assuming of course that you know regex. To locate a place between two characters, we use (?<=X)
zero-width positive lookbehind and (?=X)
zero-width positive lookahead.
public static String addHyphen(String word) {
return word.replaceAll("(?i:(?<=[a-z])(?=[0-9])|(?<=[0-9])(?=[a-z]))", "-");
}
Test
System.out.println(addHyphen("1234GRR1234GRR"));
Output
1234-GRR-1234-GRR
For full Unicode definition of "letters" and "numbers", use this regex instead:
"(?<=\\p{L})(?=\\p{N})|(?<=\\p{N})(?=\\p{L})"
Test
System.out.println(addHyphen("1234FooⅯⅭⅭⅩⅩⅩⅣḞõô"));
Output
1234-Foo-ⅯⅭⅭⅩⅩⅩⅣ-Ḟõô
Upvotes: 4