Java 程式列印帶全名的姓氏首字母


當提供全名時,該名稱的首字母將打印出來,姓氏將完全打印出來。其示例如下所述 −

Full name = Amy Thomas
Initials with surname is = A. Thomas

一個展示此示例的程式如下所示 −

示例

 線上演示

import java.util.*;
public class Example {
   public static void main(String[] args) {
      String name = "John Matthew Adams";
      System.out.println("The full name is: " + name);
      System.out.print("Initials with surname is: ");
      int len = name.length();
      name = name.trim();
      String str1 = "";
      for (int i = 0; i < len; i++) {
         char ch = name.charAt(i);
         if (ch != ' ') {
            str1 = str1 + ch;
         } else {
            System.out.print(Character.toUpperCase(str1.charAt(0)) + ". ");
            str1 = "";
         }
      }
      String str2 = "";
      for (int j = 0; j < str1.length(); j++) {
         if (j == 0)
            str2 = str2 + Character.toUpperCase(str1.charAt(0));
         else
            str2 = str2 + Character.toLowerCase(str1.charAt(j));
      }
      System.out.println(str2);
   }
}

輸出

The full name is: John Matthew Adams
Initials with surname is: J. M. Adams

現在讓我們瞭解一下上述程式。

列印名稱。然後列印名稱的首字母,即首字母。演示此程式碼片段如下所示 −

String name = "John Matthew Adams";
System.out.println("The full name is: " + name);
System.out.print("Initials with surname is: ");
int len = name.length();
name = name.trim();
String str1 = "";
for (int i = 0; i < len; i++) {
   char ch = name.charAt(i);
   if (ch != ' ') {
      str1 = str1 + ch;
   } else {
      System.out.print(Character.toUpperCase(str1.charAt(0)) + ". ");
      str1 = "";
   }
}

然後,列印名稱的整個姓氏。演示此程式碼片段如下所示 −

String str2 = "";
for (int j = 0; j < str1.length(); j++) {
   if (j == 0)
      str2 = str2 + Character.toUpperCase(str1.charAt(0));
   else
      str2 = str2 + Character.toLowerCase(str1.charAt(j));
}
System.out.println(str2);

更新於: 30-Jul-2019

9K+ 瀏覽量

開啟你的職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.