首页 > 解决方案 > 大写转换——将字符串中每个单词的首字母转换为大写

问题描述

一些测试用例不起作用。我可以知道我哪里错了。测试用例“我喜欢编程正在工作,但 idk 的其他测试用例不工作。

class Solution
{
    public String transform(String s)
    {
        // code here
       char ch;
    //  String s = "i love programming";
        String res=""; 
        ch = s.charAt(0); 
        ch = Character.toUpperCase(s.charAt(0));
        res +=ch;
        
        for(int i=1;i<s.length();i++){
                if(s.charAt(i) == ' '){
                    //System.out.println(i);
                    
                    ch = Character.toUpperCase(s.charAt(i+1));
                    res+=' ';
                    res+=ch;
                    i++;
                }else {
                    
                    res+=s.charAt(i);
                
                }
        }
        
        return res;
    }
}


//Some test cases are not working. May I know where I went Wrong?

标签: java

解决方案


这个解决方案对我来说非常有效,所有测试用例都通过了。谢谢你。

class Solution
{
    public String transform(String s)
    {
        // code here
       char ch;
    //  String s = "i love programming";
        String res=""; 
        ch = s.charAt(0); 
        ch = Character.toUpperCase(s.charAt(0));
        res +=ch;
        
        for(int i=1;i<s.length();i++){
                if(s.charAt(i-1) == ' '){
                    //System.out.println(i);
                    
                    ch = Character.toUpperCase(s.charAt(i));
                    
                    res+=ch;
              
                }else {
                    
                    res+=s.charAt(i);
                
                }
        }
        
        return res;
    }
}

推荐阅读