提供全名时,将打印姓名的首字母,并打印全名。一个例子如下:
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);