I'm writing a form of word scrambler for strings which takes all letters except for the first and last, and rotates their positions. However, I am supposed to only look at the second to second last letters. How should I only scramble from the second last letter to the second last letter?
eg scramble "string" to "srintg"
I can call Collections.rotate() on an array of characters created by splitting the string, but that will scramble the entire word.
List<String> newWordList = Arrays.asList(word.split(" "));
Collections.rotate(newWordList, -1);
String newWord = String.join("", newWordList);
I want to get the output "srintg", but instead I will get "rintgs".
Provided that your word is long enough for it to be sensible (at least four letters), you can make the approach you present work by rotating a sublist of your list:
Collections.rotate(newWordList.subList(1, newWordList.size() - 1), -1);
List.subList()
creates a view of a portion of a List
list for the exact purpose of avoiding the need for overloading List
methods with versions that operate on indexed sub-ranges of the elements. That's "fast" in the sense of fast to write, and it's fairly clear.
If you are looking for "fast" in a performance sense, however, then splitting and joining strings seems ill-advised. Fast est is probably not something we can offer, as performance needs to be tested, but if I were looking for best performance then I would test at least these general approaches:
String.toCharArray()
to obtain your word's letters in array form. for
loop to rotate the characters in the array. String
from the modified array (using the appropriate constructor). StringBuilder
to assemble the word
StringBuilder
with initial capacity equal to the word length. CharacterIterator
, appending them to the builder in the order required. This can be done in a single pass.
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.