2013-12-15 60 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(); 
相关问题