无法使用分割功能,请帮助...
假设输入= SACHIN RAMESH TENDULKAR
全部为大写。
output = 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);
}
}
答案 0 :(得分:0)
您可以使用charAt()查找空格,然后获取下一个字符吗?
答案 1 :(得分:0)
因为他们同时输入所有信息,所以您只能拨打User
一次。所以你的整个代码必须改变才能实现。考虑以下&#34;
s.nextLine()
答案 2 :(得分:0)
您可以这样做:
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);
}
示例(注意名字前后的专用空格,第二个名字后面和姓氏后面的&gt;赢得了输出):
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