Make String first letter capital in java

后端 未结 8 2084
耶瑟儿~
耶瑟儿~ 2020-12-29 04:04

As of now I\'m using this code to make my first letter in a string capital

String output = input.substring(0, 1).toUpperCase() + input.substring(1);
<         


        
相关标签:
8条回答
  • 2020-12-29 04:37

    You should have a look at StringUtils class from Apache Commons Lang lib - it has method .capitalize()

    Description from the lib:

    Capitalizes a String changing the first letter to title case as per Character.toTitleCase(char). No other letters are changed.

    0 讨论(0)
  • 2020-12-29 04:37
    Character.toString(a.charAt(0)).toUpperCase()+a.substring(1)
    

    P.S = a is string.

    0 讨论(0)
  • 2020-12-29 04:38

    Here, hold my beer

    String foo = "suresh";
    String bar = foo.toUpperCase();
    if(bar.charAt[0] == 'S'){
       throw new SuccessException("bar contains 'SURESH' and has the first letter capital").
    }
    
    0 讨论(0)
  • 2020-12-29 04:39

    Assuming you can use Java 8, here's the functional way that nobody asked for...

    import java.util.Optional;
    import java.util.stream.IntStream;
    
    public class StringHelper {
        public static String capitalize(String source) {
            return Optional.ofNullable(source)
                .map(str -> IntStream.concat(
                    str.codePoints().limit(1).map(Character::toUpperCase),
                    str.codePoints().skip(1)))
                .map(stream -> stream.toArray())
                .map(arr -> new String(arr, 0, arr.length))
                .orElse(null);
        }
    }
    

    It's elegant in that it handles the null and empty string cases without any conditional statements.

    0 讨论(0)
  • 2020-12-29 04:41

    How about this:

    String output = Character.toUpperCase(input.charAt(0)) + input.substring(1);
    

    I can't think of anything cleaner without using external libraries, but this is definitely better than what you currently have.

    0 讨论(0)
  • 2020-12-29 04:42
    class strDemo3
    {
        public static void main(String args[])
        {
            String s1=new String(" the ghost of the arabean sea");
            char c1[]=new char[30];       
            int c2[]=new int[30];
            s1.getChars(0,28,c1,0);
            for(int i=0;i<s1.length();i++)
            {
               System.out.print(c1[i]);
            }
            for(int i=1;i<s1.length();i++)
            {
               c2[i]=c1[i];
               if(c1[i-1]==' ')
               {
                   c2[i]=c2[i]-32;
               }
               c1[i]=(char)c2[i];          
            }
            for(int i=0;i<s1.length();i++)
            {
               System.out.print(c1[i]);
            }            
           }
    }
    
    0 讨论(0)
提交回复
热议问题