Reputation: 9
I'm trying to get each word and/or number/symbol combination input in a string doubled in this way:
My name is >> My My name name is is
148 !! 697 >> 148 148 !! !! 697 697
The code is 428 >> The The code code is is 428 428
I've spent a while with this and I just can't seem to figure out how to get the doubling to work properly or keep the doubled parts separated from one another.
Upvotes: 0
Views: 123
Reputation: 137259
Using, a regular expression, you can do this quite simply. The following groups all characters that aren't whitespace (\S
) and replaces them by themselves twice, using the back-reference $1
.
public static void main(String[] args) {
String[] str = { "My name is", "148 !! 697", "The code is 428" };
Pattern pattern = Pattern.compile("(\\S+)");
for (String s : str) {
String res = pattern.matcher(s).replaceAll("$1 $1");
System.out.println(res);
}
}
This prints
My My name name is is
148 148 !! !! 697 697
The The code code is is 428 428
Upvotes: 3
Reputation: 14640
By word, I assume you mean space-separated item?
String doubleit(String inpString) {
List<String> doubles = new ArrayList<String>();
String [] items = inpString.split();
for ( String item : items ) {
doubles.add( item );
doubles.add( item );
}
return doubles.join( " " );
}
Upvotes: 0
Reputation: 45339
String phrase = "My name is";
StringBuilder result = new StringBuilder();
for(String word : phrase.split(" ")) {
result.append(word).append(" ").append(word).append(" ");
}
String finalResult = result.toString().trim(); //trim() removes the last, extraneous space.
Upvotes: 1
Reputation: 131
Loop though the string and for each word append it two times to a new mutable string.
Upvotes: 0