2013-12-15 59 views
-1

我必須讓我的程序大寫一個句子的第一個字母,出於某種原因,我的代碼無法工作。我不知道爲什麼 - 我的代碼看起來應該是可行的,而且我更懂得在我的經驗不足中責怪Java中的一個「可能」錯誤。這是我到目前爲止:我怎樣才能讓我的程序大寫一個句子的第一個字母?

public class SentenceFormator { 
    public static String format(String str){ 
     String fmts = str; 
     String temp; 

     //Finds first subString makes it capitalized and replaces it in original String. 
     temp = fmts.substring(0, 1).toUpperCase(); 
     fmts = fmts.replaceFirst(fmts.substring(0,1), temp); 
     //Makes all other letters after beginning of sentence lower-case. 
     fmts = fmts.substring(1,str.length()-1).toLowerCase(); 
     //Capitalizes all i's in the String. 
     fmts = fmts.replaceAll(" i ", " I "); 
     //Take away white spaces at the end and beginning of the String. 
     fmts = fmts.trim(); 
     //Add punctuation if not already there. 
     if(!fmts.endsWith(".")||fmts.endsWith("!")||fmts.endsWith("?")){ 
      fmts = fmts.concat("."); 
     } 
     //Takes away 

     for(int i = 0; i<str.length();i++){ 

     } 
     return fmts; 
    } 
} 
+1

難道只是我還是你的標題不同的F /什麼你問?所以你只需要做「帶走」功能?如果是這樣,請更改標題 – Coffee

+5

@Adel請在評論中使用整個單詞。這不是一條短信:-) –

+1

首先定義「句子」。 –

回答

0

看看你真的這樣做在你的代碼

//you store uppercase version of first letter in `temp` 
temp = fmts.substring(0, 1).toUpperCase(); 
//now you replace first letter with upper-cased one 
fmts = fmts.replaceFirst(fmts.substring(0,1), temp); 

,現在時間是什麼爲自己的錯誤

//here you are storing in `fmts` as lower-case part **after** first letter 
//so `fmts =" Abcd"` becomes `fmts = "bcd"` 
fmts = fmts.substring(1,str.length()-1).toLowerCase(); 

要糾正它,你可以像新的字符串的開頭添加temp

fmts = temp + fmts.substring(1).toLowerCase();//BTW you can use `substring(1)` 
             //instead of `substring(1,str.length()-1)` 
+0

我做到了這一點,我仍然得到「h」作爲第一個字符。 :P – CameronCarter

+0

@CameronCarter你可以發佈你在測試中使用的句子嗎? – Pshemo

+0

@CameronCarter你也可以發佈你如何使用你的方法嗎?我懷疑你可能沒有用這種方法的結果辭職你的字符串。 – Pshemo

0
String str = " hello world" 

減少空間一(避免在前面的空格)

str = str.trim().replaceAll(" +", " "); 

首字母大寫和小寫的一切(加上他們倆)

str = str.substring(0,1).toUpperCase() + str.substring(1,str.length()).toLowerCase(); 
相關問題