I am new to java and I have been trying to solve a problem which I feel might have a simpler answer than my code.The problem was to print the initials of a user input name of any length along with the full surname.But this has to be done without any String.split() or arrays.I tried getting the user to input his name one word at a time, but is there any there a possible way to get the whole name at once and do as required. My code is as follows:
import java.io.*;
public class Initials {
public static void main(String[]args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of words your name contains");
int n=Integer.parseInt(br.readLine());
String str="";
for(int x=1;x<=n-1;x++){
System.out.println("Enter your name's word number:"+" "+x);
String s=br.readLine();
String st=s.toUpperCase();
char ch=st.charAt(0);
str=str+ch+".";
}
System.out.println("Enter your surname");
String sur=br.readLine();
str=str+" "+sur.toUpperCase();
System.out.println(str);
}
}
Use a regular expression (namely (?<=\w)\w+(?=\s)
):
String name = "John Paul Jones"; // read this from the user
System.out.println(name.replaceAll("(?<=\\w)\\w+(?=\\s)", "."));
J. P. Jones
No split()
, no arrays :)
A little explanation: We essentially want to replace all letters of each word that is followed by a whitespace character except the first letter, with a .
character. To match such words, we use (?<=\w)\w+(?=\s)
:
(?<=\w)
is a positive lookbehind; it checks that a word-character exists at the start of the match but does not include it in the match itself. We have this component because we don't want to match the first character of each name, but rather all but the first (except for the last name, which we'll deal with shortly).\w+
matches any continuous string of word characters; we use this to match the rest of the name.(?=\s)
is a positive lookahead; it checks that our match is followed by a whitespace character, but does not include it in the match itself. We include this component because we don't want to replace anything on the last name, which should not be followed by a whitespace character and hence should not match the regular expression.