Hello I am trying to change the place of characters in a string. But the first and last have to stay like they are. For example:
String str = "String test print out";
The output should be for example:
Sirntg tset pirnt out
The first and last charakter of each word have to stay the rest have to change randomly: Here is the code I already did, I tryed to splitt the element of the string in an array and splitt them but its not working:
import java.util.*;
public class Main
{
public static void main(String[] args) {
String str = "String test out";
String[] words = str.split("\\s");
Random rnd = new Random();
ArrayList<Integer> digitList = new ArrayList<Integer>();
for(int j = 0;0<=words[].length();j ){
int lst = words[j].length();
char first = words[j].charAt(0);
char last = words[j].charAt(words[j].length() - 1);
for(int i =1, random = 0; i < words[j].length()-1; i ){
do{
random = rnd.nextInt(words[j].length()-2) 1;
}while(digitList.contains(random));
digitList.add(random);
System.out.print(words[j].charAt(random));
}
}
}
}
CodePudding user response:
You could make use of some nifty functionality in Java's collection framework:
public static void main(String[] args) {
String str = "String test out";
for (String word : str.split("\\s")) {
List<Character> chars = word.chars()
.mapToObj(e -> (char) e)
.collect(Collectors.toList());
// shuffle the letters in the word, except for the first one and last one
Collections.shuffle(chars.subList(1, chars.size() - 1));
String shuffledWord = chars.stream()
.map(String::valueOf)
.collect(Collectors.joining());
System.out.println(shuffledWord);
}
}
CodePudding user response:
Here is a really efficient way to do it. Instead of splitting, changing strings and merging them back together, create a single StringBuilder and use a Pattern to go through each word, scramble them and then return the string.
/** This pattern matches a word, and group 1 excludes the first and last letter. */
static final Pattern WORD = Pattern.compile("\\b\\w(\\w{2,})\\w\\b");
public String scrambleWords(String input) {
Random random = new Random();
StringBuilder s = new StringBuilder(input);
Matcher m = WORD.matcher(input);
while (m.find()) {
int start = m.start(1);
int end = m.end(1);
for (int i = start; i 1 < end; i ) {
int j = random.nextInt(i 1, end);
char c1 = s.charAt(i);
char c2 = s.charAt(j);
s.setCharAt(i, c2);
s.setCharAt(j, c1);
}
}
return s.toString();
}