Enter a line of text. No punctuation please.
Java is the language I have rephrased that line to read: 开发者_Python百科Is the language Java
This is an example, and I only know the char method, but I don't know how to move the first word to the end. which string method can I use?
What to do:
- Split the sentence using String.split();
- Create a List from the items
- Reorder the List
- Join the List items using a space
Implementation in plain Java:
final String s = "Java Is The Language";
final List<String> list =
new ArrayList<String>(Arrays.asList(s.split("\\s+")));
list.add(list.size() - 1, list.remove(0));
final StringBuilder sb = new StringBuilder();
for(final String word : list){
if(sb.length() > 0){
sb.append(' ');
}
sb.append(word);
}
System.out.println(sb.toString());
Implementation using Guava:
final String s = "Java Is The Language";
final List<String> list =
Lists.newArrayList(Splitter
.on(CharMatcher.WHITESPACE)
.omitEmptyStrings()
.split(s));
list.add(list.size() - 1, list.remove(0));
System.out.println(Joiner.on(' ').join(list));
I think you mean Java (and not JavaScript):
final String delimiter = " ";
String input = /* whatever */;
String[] tokens = input.split(delimiter);
String output = "";
for (int i = 1; i<tokens.length; i++)
{
output += input[i] + delimiter;
}
output += tokens[0];
System.out.println(output);
Incidentally, this code could/would look very similar in JavaScript:
var delimiter = " ",
input = /* whatever */,
tokens = input.split(delimiter),
output = [],
len = tokens.length,
i;
for (i = 1; i<len; i++)
{
output.push(input[i]);
}
output.push(tokens[0]);
output = output.join(delimiter);
alert(output);
Substring, indexOf and length. Try those out.
精彩评论