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+ 浏览量

开启你的职业

通过完成课程获得认证

开始
广告