Java中将第一个单词移到最后一个位置

3

我该如何将Jave is the language转换为Is the language Java呢?下面是我的代码,但我觉得出现了一些问题。

public class Lab042{
    public static final String testsentence = "Java is the language";
    public static void main(String [] args) {
        String rephrased = rephrase( testsentence);
        System.out.println("The sentence:"+testsentence);
        System.out.println("was rephrased to:"+rephrased);
    }

    public static String rephrase(String testsentence) {
        int index = testsentence.indexOf (' ');
        char c = testsentence.charAt(index+1);
        String start = String.valueOf(c).toUpperCase();
        start += testsentence.substring(index+2);
        start += " ";
        String end = testsentence.substring(0,index);
        String rephrase = start + end;
    }
}

你应该在 rephrase() 中使用 StringBuilder - user180100
Leo,如果这里有正确的答案,请点赞它。 - Scary Wombat
4个回答

3
您没有返回新短语。在您的rephrase()方法底部添加以下内容:
return rephrase;

2
使用 String.split。
String testsentence = "Java is the language";
String [] arr = testsentence.split (" ");
String str = "";

for(int i = 1; i < arr.length; ++i)
   str += arr[i];

return str + arr[0];

对于真实世界的程序,请使用StringBuilder而不是连接字符串。


1
你可以按照以下方式修改你的rephrase()方法。这样更易读且清晰。
public static String rephrace(String testsentence) {
    //Separate the first word and rest of the sentence
    String [] parts = testsentence.split(" ", 2);
    String firstWord = parts[0];
    String rest = parts[1];

    //Make the first letter of rest capital
    String capitalizedRest = rest.substring(0, 1).toUpperCase() + rest.substring(1);

    return capitalizedRest + " " + firstWord;
}

我没有包含验证错误检查。但在生产代码中,您应该在使用索引访问它们之前验证数组和字符串的长度。


0
import java.util.Scanner;

public class prograProj3
{

    public static void main(String[] args)
    {
        Scanner keyboard = new Scanner(System.in);
        String inputText, firstWord2, firstWord;
        System.out.println("Enter a line of text. No punctuation please.");
        inputText = keyboard.nextLine();
        firstWord = inputText.substring(0, inputText.indexOf(' '));
        inputText = (inputText.replaceFirst(firstWord, "")).trim();
        inputText = ((inputText.substring(0, 1))).toUpperCase() + inputText.substring(1);
        System.out.println(inputText + " " + firstWord);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接