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

时间:2016-03-07 06:09:18

标签: java

如何让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;
    }
}

4 个答案:

答案 0 :(得分:3)

您没有返回新短语。在方法rephrase()的底部,输入:

return rephrase;

答案 1 :(得分: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而不是连接字符串

答案 2 :(得分: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;
}

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

答案 3 :(得分: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);
    }
}