简体   繁体   中英

How to change the words in a string and reprint the original string but with the new arrangement of words?

Code :

String one, two, three,four, five,six,seven,eight;
Scanner kbrd = new Scanner(System.in);
System.out.println("please enter a phrase, and then pick three words that you want to switch");
one= kbrd.nextLine();
two= kbrd.next() +" ";
three = kbrd.next()+" ";
four = kbrd.next()+ " ";
two.toLowerCase();
three.toLowerCase();
four.toLowerCase();
seven = two+three+four;
System.out.println(one.indexOf(two));
System.out.println(one.lastIndexOf(four));
five = four.toUpperCase()+three+two.toUpperCase();
System.out.println(five);
eight = one.replace(seven.trim(),five.trim());
System.out.println(eight)

It works but when someone inputs the second user input with Name is George it won't re-arrange the words to say GEORGE IS NAME. It works if the two user inputs are My name is george. name is george. Any ideas how to fix this? My theory is that it can't find it in the orginal sentence and therfore it doesn't know what to replace because what it is replacing isn't in the original.

What you could do is use Collections.Shuffle()

Your new code would look like :

eight = one.replace(seven.trim(),five.trim());
// System.out.println(eight)
List<String> sentence = Arrays.asList(eight.trim().split(" "));
Collections.shuffle(sentence);
for(String str : sentence) {
   System.out.println(str+" ");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM