What is the best way to get the first letter from a string in Java, returned as a string of length 1?

前端 未结 5 1609
自闭症患者
自闭症患者 2020-12-08 08:43

Assume the following:

String example      = \"something\";
String firstLetter  = \"\";

Are there d

5条回答
  •  隐瞒了意图╮
    2020-12-08 09:36

    Performance wise substring(0, 1) is better as found by following:

        String example = "something";
        String firstLetter  = "";
    
        long l=System.nanoTime();
        firstLetter = String.valueOf(example.charAt(0));
        System.out.println("String.valueOf: "+ (System.nanoTime()-l));
    
        l=System.nanoTime();
        firstLetter = Character.toString(example.charAt(0));
        System.out.println("Character.toString: "+ (System.nanoTime()-l));
    
        l=System.nanoTime();
        firstLetter = example.substring(0, 1);
        System.out.println("substring: "+ (System.nanoTime()-l));
    

    Output:

    String.valueOf: 38553
    Character.toString: 30451
    substring: 8660
    

提交回复
热议问题