How can I get the first letter of a word and bring it to the end?
Get the first letter of a word and bring it to the end
1.4k Views Asked by Phineas At
4
There are 4 best solutions below
0
On
for (int i = 0; i < word.length(); i++) {
firstLetter = word.charAt(0);
word = word.substring(1, word.length());
System.out.println(firstLetter + word);
word += firstLetter;
}
0
On
A sightly different approach: leave the word as is, and iterate through the permutations based on substrings. After all: "omputerc" is just [omputer] + [c], which is [c][omputer] swapped; the next iteration is "mputerco" which is just [mputer] + [co], or [co][mputer] swapped, and so forth:
String head, tail;
for (int i = 0, last = word.length()-1; i<last; i++) {
head = word.substring(0,i);
tail = word.substring(i,last);
System.out.println(tail + head);
}
We leave the word as is, grab the head and tail substrings, and print them in reverse order, producing exactly what you need.
You are taking the
ith letter each time, when you should take the first letter with index0each time. Changeto