gpt4 book ai didi

java - 如何在不使用 split() 的情况下提取名字和中间名的首字母和姓氏,就像在java中一样

转载 作者:太空宇宙 更新时间:2023-11-04 11:32:32 25 4
gpt4 key购买 nike

无法使用分割功能,请帮忙...

假设输入 = SACHIN RAMESH TENDULKAR 全部大写。

输出=Tendulkar.S.R

我尝试的代码是使用字符串数组还有其他选择吗?-

import java.util.*;
public class substr {

public static void main(String[] args) {
// TODO Auto-generated method stub

Scanner s = new Scanner(System.in);
String[] array = new String[3];
System.out.println("Please enter first name,middle name and
last name in capital");

for (int i = 0; i < array.length;i++){
array[i] = s.nextLine();
}
char f=array[0].charAt(0);
char m=array[1].charAt(0);
char sn=array[2].charAt(0);
String sn1="";
for(int i=1;i<array[2].length();i++){
char ch=array[2].charAt(i);
if(ch>=65 && ch<90){
ch=(char)(ch+32);
}
sn1+=ch;

}
System.out.println(sn+sn1+"."+f+"."+m);
}

}

最佳答案

你可以这样做:

import java.util.Scanner;
public class Substr {

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter First Name, Middle Name and Last Name");
String fullName = input.nextLine().toUpperCase(); // convert input to UPPERCASE
while(fullName.charAt(fullName.length()-1)==' '){ // remove all spaces at the end of the input because it may cause problem
fullName = fullName.substring(0, fullName.length()-1);
}
while(fullName.charAt(0)==' '){ // remove all spaces at the beginning of the input because it may cause problem
fullName = fullName.substring(1, fullName.length());
}

String firstName = "", middleName ="", lastName ="";

firstName = fullName.substring(0, fullName.indexOf(' ')); // the first name is from the beginning to the first occurrence of space

int noOfSpaces=0;
for(int i=firstName.length(); i<fullName.length(); i++){// count the number of spaces after the first name in case user by mistake
// entered more than one space
if (fullName.charAt(i)==' '){
noOfSpaces++;
}
else{
break;
}
}
middleName = fullName.substring(firstName.length()+noOfSpaces, fullName.lastIndexOf(' ')); // the second name (remember we removed the spaces at the end)

lastName = fullName.substring(fullName.lastIndexOf(' ')+1,fullName.length()); // the last name

String customizedName = firstName + "." + middleName.charAt(0) + "." + lastName.charAt(0);
System.out.println(customizedName);
}

示例(请注意名字前后、名字后面和姓氏后面的故意空格 -> 不会破坏输出):

Please enter First Name, Middle Name and Last Name
Muhammad Yahya Almardeny
MUHAMMAD.Y.A

另一个例子(正常):

Please enter First Name, Middle Name and Last Name
Muhammad Yahya Almardeny
MUHAMMAD.Y.A

关于java - 如何在不使用 split() 的情况下提取名字和中间名的首字母和姓氏,就像在java中一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43644177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com