2016-03-07 128 views
3

我該如何讓Jave is the languageIs the language Java 這是我的代碼,但我認爲這裏有一些問題。將第一個單詞移到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; 
    } 
} 
+0

你應該在'rephrase()'中使用'StringBuilder'。 – 2016-03-07 06:12:18

+0

獅子座,如果這裏有正確的答案,請注意。 –

回答

3

您沒有返回新短語。在你的方法重新整理()的底部,把這個:

return rephrase; 
+0

謝謝,我忘了! –

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而不是串聯絃樂雖然

+0

歡呼@ uma-kanth –

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; 
} 

我沒有包含驗證錯誤檢查。但是在生產代碼中,在使用索引訪問它們之前,應驗證數組和字符串的長度。

相關問題