有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java大写转换将字符串中每个单词的第一个字母转换为大写

有些测试用例不起作用。我可以知道我哪里出错了吗。“我爱编程”的测试用例正在工作,但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?

共 (3) 个答案

  1. # 1 楼答案

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

    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;
        }
    }
    
  2. # 2 楼答案

    我尽我所能理解你的代码,因为我认为格式在降价过程中受到了一些破坏,但我认为这与你的解决方案非常接近:

    public class MyClass {
        public static void main(String args[]) {
          int i = 0; 
          String greet = "hello world"; 
          String res = ""; 
          res += Character.toUpperCase(greet.charAt(i++)); 
          for (; i < greet.length(); i++){
              if (greet.charAt(i) == ' '){
                  res = res + greet.charAt(i) + Character.toUpperCase(greet.charAt(i + 1) );
                  i++; 
              }else{
                  res += greet.charAt(i); 
              }
          }
          System.out.println(res);
        }
         
    }
    

    对我来说,这是可行的,但这是假设空格只出现在单词之间。也许你问题的答案在于这些测试用例,更重要的是这些测试用例背后的假设。如果可以的话,尝试收集更多信息:)

  3. # 3 楼答案

    有人试图将大写字母设置为空格后的下一个字符(只有当该字符是字母时,才应这样做,如果该字符可用,则应设置为)。同样地,句子的第一个字符是大写的,不检查第一个字母是否是字母

    最好使用布尔标志,在对字母应用大写字母时,应重置该标志。此外,应该使用StringBuilder,而不是在循环中连接字符串

    因此,在添加更多规则后,改进后的代码可能如下所示:

    • 将单词中由字母和/或数字组成的第一个字母大写
    • 单词之间用任何非字母/非数字字符分隔,但'等缩略语中使用的I'm, there's除外
    • 检查null/空输入
    public static String transform(String s) {
        if (null == s || s.isEmpty()) {
            return s;
        }
        boolean useUpper = true; // boolean flag
        StringBuilder sb = new StringBuilder(s.length());
            
        for (char c : s.toCharArray()) {
            if (Character.isLetter(c) || Character.isDigit(c)) {
                if (useUpper) {
                    c = Character.toUpperCase(c);
                    useUpper = false;
                }
            } else if (c != '\'') { // any non-alphanumeric character, not only space
                useUpper = true; // set flag for the next letter
            }
            sb.append(c);
        }
            
        return sb.toString();
    }    
    
    

    测试:

    String[] tests = {
        "hello world",
        "  hi there,what's up?",
        "-a-b-c-d",
        "ID's 123abc-567def"
    };
    
    for (String t : tests) {
        System.out.println(t + " -> " + transform(t));
    }
    

    输出:

    hello world -> Hello World
      hi there, what's up? ->   Hi There,What's Up?
    -a-b-c-d -> -A-B-C-D
    ID's 123abc-567def -> ID's 123abc-567def
    

    更新

    Java 9提供的正则表达式和^{}也有助于大写单词中的第一个字母:

    // pattern to detect the first letter
    private static final Pattern FIRST_LETTER = Pattern.compile("\\b(?<!')(\\p{L})([\\p{L}\\p{N}]*?\\b)");
    public static String transformRegex(String s) {
        if (null == s || s.isEmpty()) {
            return s;
        }
            
        return FIRST_LETTER.matcher(s)
            .replaceAll((mr) -> mr.group(1).toUpperCase() + mr.group(2));
    }
    

    这里:

    • \b-单词边界
    • (?<!')如上所述,对'进行负查找,即匹配前面没有'的字母
    • \p{L}-单词中的第一个字母(Unicode)
    • ([\p{L}\p{N}]*\b)-后跟可能为空的字母/数字序列