Reputation: 329
I'm struggling with this code. Return of this one is eg: "JS John Smith" but when I try to put two names plus surname all I get is a mess. I wish to get when I type eg: "John William Smith" something like this: "JW Smith", anybody know hot to do it?
import java.io.*;
import java.io.BufferedReader;
public class ex54 {
public static void main(String[] args) {
System.out.print("Enter your name: ");
BufferedReader br = new BufferedReader(new InputStreamReader (System.in));
String fullName = null;
try{
fullName = br.readLine();
} catch (IOException ioe) {
System.out.println("Error");
System.exit(1);
}
int spacePos = fullName.indexOf(" ");
// String firstName = fullName.substring(0, spacePos);
// String secondName = fullName.substring(1, spacePos);
String firstInitial = fullName.substring(0, 1);
String secondInitial = fullName.substring(spacePos+1, spacePos+2);
String userName = (firstInitial + secondInitial + " ").concat(fullName);
System.out.println("Hello, your user name is: " + userName);
}
}
}
Upvotes: 0
Views: 707
Reputation: 159086
Just for kicks, here is an implementation using regular expressions:
private static String firstNamesToInitials(String name) {
StringBuilder buf = new StringBuilder();
Matcher m = Pattern.compile("\\b([A-Z])[A-Za-z]*\\b").matcher(name);
String lastName = null;
while (m.find()) {
buf.append(m.group(1));
lastName = m.group();
}
if (buf.length() <= 1)
return lastName;
buf.setCharAt(buf.length() - 1, ' ');
return buf.append(lastName).toString();
}
Test
System.out.println(firstNamesToInitials("Cher"));
System.out.println(firstNamesToInitials("John Smith"));
System.out.println(firstNamesToInitials("John William Smith"));
System.out.println(firstNamesToInitials("Charles Philip Arthur George"));
System.out.println(firstNamesToInitials("Pablo Diego José Francisco de Paula Juan Nepomuceno María de los Remedios Cipriano de la Santísima Trinidad Ruiz y Picasso"));
Output
Cher
J Smith
JW Smith
CPA George
PDFPJNRCTR Picasso
Upvotes: 0
Reputation: 13
int spacePos = -1;
System.out.print("Hello, your user name is:");
do {
System.out.print(" "+fullName.substring(spacePos+1, spacePos+2));
fullName = fullName.substring(spacePos+1);
spacePos = fullName.indexOf(" ");
}while(spacePos != -1);
System.out.println("\b"+fullName);
Upvotes: 0
Reputation: 2084
You can split the name, assuming you are given a three-name string:
String[] names = fullname.split(" ");
System.out.println("" + names[0].charAt(0) + names[1].charAt(0) + " " + names[2]);
Upvotes: 1