简体   繁体   中英

How can I move the first word to the end?

Enter a line of text. No punctuation please.
Java is the language
I have rephrased that line to read:
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:

  1. Split the sentence using String.split();
  2. Create a List from the items
  3. Reorder the List
  4. 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.

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