In: Computer Science
How do I get the first initial of a first, middle, and last name? Also when I look to count characters in the name I want to be abel to count the spaces in-between the names how can i do this?
In order to get the the initials of a name, i.e., the first letters of first name, middle name and last name, we have to find the positions of the space. Let's see how it can be done with an example.
Say, the name is "Dennis MacAlistair Ritchie". Here we can see that space is present before M and R. We will have to position of the space and then choose the letter which is just after the space to get the initials of the middle name and last name. In order to find the initial of the first letter we just have to pick the first letter of the given name, here D.
Now the question arise how to find the spaces and also how to count it which is the second part of your question. Todo that all we have to is check whether each character is letter or not, i.e., whether each character lies between a-z or A-Z, if it does not lie there then it means that the character is space (since in general name contains only letters spaces). This process enables you to detec whether a given character is letter or not. If you just want to identify space, then simply check whether the given character is space or not. In order to count the number of spaces, just increment a counter whenever a space in found.
Here is a Java code for better understanding:
public class Main
{
public static void main(String[] args) {
Initial("Dennis MacAlistair
Ritchie");
}
public static void Initial(String a)
{
String s=a.charAt(0)+""; //initial letter of first
name
int c=0; //to count the number of spaces
for(int i = 0; i < a.length(); i++)
{
if(a.charAt(i) == ' ')
{
s=s+a.charAt(i+1); //to add the initial letters of
middle and last name
c++; //incremented when space is found
}
}
System.out.println("The initials of "+a+" is "+s+
"\nThe space count is : "+c);
}
}
Please refer to the screenshot of the code to understand the indentation of the code:
Output:
For any doubts or questions comment below.