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

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

Assume the following:

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

Are there d

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-08 09:40

    import java.io.*;
    class Initials {
    
        public static void main(String args[]) throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String s;
            char x;
            int l;
            System.out.print("Enter any sentence: ");
            s = br.readLine();
            s = " " + s; //adding a space infront of the inputted sentence or a name
            s = s.toUpperCase(); //converting the sentence into Upper Case (Capital Letters)
            l = s.length(); //finding the length of the sentence
            System.out.print("Output = ");
    
            for (int i = 0; i < l; i++) {
                x = s.charAt(i); //taking out one character at a time from the sentence
                if (x == ' ') //if the character is a space, printing the next Character along with a fullstop
                    System.out.print(s.charAt(i + 1) + ".");
            }
        }
    }
    

提交回复
热议问题