I am receiving full name, i need to split this into Salutation, Firstname and lastname.
for eg.
Steve Emond==> Steve as Firstname , Emond as lastname(here Salutation is Empty)
Mr Chris Barker ==> Mr as Salutation, Chris as Firstname , Barker as lastname
Justin ==> Justin as lastname(Salutation and Firstname are empty)
Note: received Miss,Mr,Mrs as Salutation values.
Code:
String FirstName="";
String fullName="Barker";
String[] nameArray=fullName.split(" ");
if(nameArray.length<3)
{
System.out.println("Salutation: " + nameArray[0]);
System.out.println("LastName: " + nameArray[1]);
System.out.println("FirstName: " + FirstName);
}else if(nameArray.length>=3){
System.out.println("Salutation: " + nameArray[0]);
System.out.println("LastName: " + nameArray[nameArray.length - 1]);
for (int index = 1; index < nameArray.length - 1; index++) {
FirstName = FirstName + " " + nameArray[index];
}
System.out.println("FirstName: " + FirstName.trim());
}
The above code works fine when all values given in input( ie Mr Chris Barker ), for the remaining case it failed. can anyone provide me the solution for this?
Method 1:
String fullName="Steve Emond";
String[] nameArray=fullName.split(" ");
if(nameArray.length==1)
{
System.out.println("LastName: " + nameArray[0]);
}else if(nameArray.length==2){
System.out.println("FirstName: " + nameArray[0]);
System.out.println("LastName: " + nameArray[1]);
}
else if(nameArray.length==3){
System.out.println("Salutation: " + nameArray[0]);
System.out.println("FirstName: " + nameArray[1]);
System.out.println("LastName: " + nameArray[2]);
}
Using Regex Method 2:
String fullName="Mr Justin raj Savarimuthu";
Pattern pattern = Pattern.compile(new String ("(Mr\\s|Miss\\s|Mrs\\s)"));
if(fullName.matches("(Mr\\s|Miss\\s|Mrs\\s).*"))
{
System.out.println("Salutation:"+fullName.substring(0,fullName.indexOf(' ')));
fullName=pattern.split(fullName)[1].trim();
}
String[] parts = fullName.split(" ");
String firstName="";
for(int i=0;i<parts.length-1;i++)
{
firstName=firstName+parts[i]+" ";
}
if(firstName!="")
System.out.println("FirstName:"+firstName);
System.out.println("LastName:"+parts[parts.length-1]);
Related
public String Cite()
{
String authorsList = "";
Collections.sort(authors);
for(Author a: authors)
{
authorsList += a.firstName.toUpperCase().charAt(0) + ". " + a.lastName + ", ";
}
String cite = authorsList + "\"" + title + "\", " + venue + "(" + getAcronym() + ")" + " , " +
publisher;
return cite;
}
How would I go about adding the word "and" to separate the last two names of the list?
Use a for loop with index.
for (int i = 0; i < authors.size(); ++i) {
if (i == authors.size() - 2) {
authorsList += a.firstName.toUpperCase().charAt(0) + ". " + a.lastName + "and ";
} else {
authorsList += a.firstName.toUpperCase().charAt(0) + ". " + a.lastName + ", ";
}
}
public static String Cite(ArrayList<Author> authors){
String authorsList = "";
Collections.sort(authors, new CustomComperator());
int size = authors.size();
int count = 0;
for(Author a: authors) {
if (size ==1) {
authorsList = a.firstName.toUpperCase().charAt(0) + ". " + a.lastName;
}
else if (count == size-2) {
authorsList += a.firstName.toUpperCase().charAt(0) + ". " + a.lastName ;
}
else if (count == size - 1) {
authorsList += " and " + a.firstName.toUpperCase().charAt(0) + ". " + a.lastName ;
}
else{
authorsList += a.firstName.toUpperCase().charAt(0) + ". " + a.lastName + ", ";
}
count ++;
}
return authorsList;
}
You should use a normal for loop, so you can detect that you're on the first and/or last element.
Other changes:
Remove the , after the last author.
Use StringBuilder to build a String.
List<Author> authors = new ArrayList<>(List.of(
new Author("Stephen", "King"),
new Author("John", "Grisham"),
new Author("William", "Shakespeare"),
new Author("Charles", "Dickens") ));
Collections.sort(authors);
StringBuilder buf = new StringBuilder();
for (int i = 0; i < authors.size(); i++) {
Author a = authors.get(i);
if (i != 0)
buf.append(i < authors.size() - 1 ? ", " : " and ");
buf.append(a.firstName.toUpperCase().charAt(0) + ". " + a.lastName);
}
String authorsList = buf.toString();
System.out.println(authorsList);
Output
C. Dickens, J. Grisham, S. King and W. Shakespeare
Oxford comma
Whether or not you want , comma before and (Oxford comma) is of course entirely up to you.
buf.append(i < authors.size() - 1 ? ", " : ", and ");
Output
C. Dickens, J. Grisham, S. King, and W. Shakespeare
UPDATE
Since all 4 other answers at this time gave bad result for a single Author, here is test result for various number of authors.
Full Test
List<Author> allAuthors = List.of(
new Author("Stephen", "King"),
new Author("John", "Grisham"),
new Author("William", "Shakespeare"),
new Author("Charles", "Dickens") );
for (int aCount = 0; aCount <= allAuthors.size(); aCount++) {
List<Author> authors = new ArrayList<>(allAuthors.subList(0, aCount));
Collections.sort(authors);
StringBuilder buf = new StringBuilder();
for (int i = 0; i < authors.size(); i++) {
Author a = authors.get(i);
if (i != 0)
buf.append(i < authors.size() - 1 ? ", " : " and ");
buf.append(a.firstName.toUpperCase().charAt(0) + ". " + a.lastName);
}
String authorsList = buf.toString();
System.out.println(aCount + ": \"" + authorsList + "\"");
}
Output
0: ""
1: "S. King"
2: "J. Grisham and S. King"
3: "J. Grisham, S. King and W. Shakespeare"
4: "C. Dickens, J. Grisham, S. King and W. Shakespeare"
If you want to do the same without loops you could:
Define a toString or similar method inside your Author class:
class Author{
String firstName;
String lastName;
Author(String firstName,String lastName){
this.firstName=firstName;
this.lastName=lastName;
}
#Override
public String toString(){
return String.format("%s. %s",this.firstName.toUpperCase().charAt(0), this.lastName);
}
}
And use the Collectors.joining to create the initial list (comma separated).
List<Author> authors = Arrays.asList(new Author("Jules", "Verne"),
new Author("Pablo", "Neruda"), new Author("JK", "Rowling"));
authors.sort(Comparator.comparing(a -> a.lastName));
StringBuffer result = new StringBuffer(
authors.stream().limit(authors.size() - 1).map(a -> a.toString()).collect(
Collectors.joining(" ,")));
And after that, add the last "and":
if (authors.size() > 1) {
result.append(String.format(" and %s", authors.get(authors.size() - 1).toString()));
} else {
result.append(authors.get(authors.size() - 1).toString());
}
System.out.println(result);
Output: P. Neruda ,J. Rowling and J. Verne
Trying to work out a homework problem that demands:
Changes a name so that the last name comes first.
Example: "Mary Jane Lee" will return "Lee, Mary Jane".
If name has no spaces, it is returned without change.
After doing some research it seems I can do this with the Split method, but we've not learned that yet.
The thing is I've worked out the code and it seems to work when spaces
and a full name is entered, but when there's no middle name or no spaces to separate the character, I get the error:
when the name entered is simply: Harry Smith
java.lang.StringIndexOutOfBoundsException: String index out of range: -7
and
java.lang.StringIndexOutOfBoundsException: String index out of range: -1
when the name is Sarah
This is my code, but I'm not sure how to fix it:
public class Names {
public static String lastNameFirst(String name) {
int firstIndex = name.indexOf(" ");
int secondIndex = name.indexOf(" ", firstIndex + 1);
String firstName = name.substring(0, name.indexOf(" "));
String middleName = name.substring(firstIndex + 1, secondIndex);
String lastName = name.substring(secondIndex + 1);
String result = "";
result = lastName + ", " + firstName + " " + middleName;
return result;
}
}
Thanks in advance!!
using split and a switch would be a lot easier
String name = "Mary Jane Lee";
String arr[] = name.split (" ");
switch (arr.length) {
case 1:
System.out.println(name);
break;
case 2:
System.out.println(arr[1] + ", " + arr[0]);
break;
default:
System.out.println(arr[2] + ", " + arr[0] + " " + arr[1]);
}
A more robust way is to use lastIndexOf to find the last space:
int lastSpace = name.lastIndexOf(' ');
if (lastSpace != -1) {
String lastName = name.substring(lastSpace + 1);
String partBeforeLastName = name.substring(0, lastSpace);
return lastName + ", " + partBeforeLastName;
} else {
return name;
}
You don't actually really care about the other space (if it's there at all), since the first and middle names stay in the same relative order.
(Generally, there are lots of falsehoods that programmers believe about names; but let's put those aside for the purpose of the exercise.)
Your code assumes that the input String contains at least two spaces. When that assumption is wrong (as in the inputs "Harry Smith" and "Sarah"), you get an exception.
You must check whether firstIndex and secondIndex are positive before using their values.
The problem is that your code excepts that there are 3 names. It does not handle when there are less names.
public static String lastNameFirst(String name)
{
int firstIndex = name.indexOf(" ");
if ( firstIndex >= 0 )
{
int secondIndex = name.indexOf(" ", firstIndex + 1 );
String firstName = name.substring(0, firstIndex);
if ( secondIndex >= 0 ) // we have 3 names
{
String middleName = name.substring(firstIndex + 1, secondIndex);
String lastName = name.substring(secondIndex + 1);
return lastName + ", " + firstName + " " + middleName;
}
else // we have 2 names
{
String lastName = name.substring(firstIndex + 1);
return lastName + ", " + firstName;
}
}
else // have only one name
return name;
}
Should worth trying lastIndexOf(), too:
public static String lastNameFirst(String name)
{
int lastIndex = name.lastIndexOf(" ");
if ( lastIndex >= 0 ) // have at least 2 names
{
String firstNames = name.substring(0,lastIndex);
String lastName = name.substring(lastIndex + 1);
return lastName + ", " + firstNames;
}
}
else // have only one name
return name;
}
Also, could try a different approach, split the name into an array, something like this:
public static String lastNameFirst(String name)
{
String[] parts = name.split(" ");
switch ( parts.length )
{
case 1:
return name;
case 2:
return parts[1] + ", " + parts[0];
case 3:
return parts[2] + ", " + parts[0] + " " + parts[1];
}
}
I'm not exactly a beginner in Java, but I'm also not an expert. Is there any way to shorten this code so that it takes up less space and possibly fewer lines?
JOptionPane.showMessageDialog(null, "The student's names are: "
+ roster[0][0] + " " + roster[1][0] + ", "
+ roster[0][1] + " " + roster[1][1] + ", "
+ roster[0][2] + " " + roster[1][2] + ", and "
+ roster[0][3] + " " + roster[1][3] + ".");
Let's refactoring the code step by step
introduce variables to remove duplication.
T[] col1 = roster[0];
T[] col2 = roster[1];
String content = col1[0] + " " + col2[0] + ", "
+ col1[1] + " " + col2[1] + ", "
+ col1[2] + " " + col2[2] + ", and "
+ col1[3] + " " + col2[3] + ".";
JOptionPane.showMessageDialog(null,"The student's names are: " + content);
separate string concatenation into multi-assignments, then all assignments are the same except the last one.
int i = 0;
String content = "";
content += col1[i] + " " + col2[i] + ", ";i++;
content += col1[i] + " " + col2[i] + ", ";i++;
content += col1[i] + " " + col2[i] + ", ";i++;
content += "and " + col1[i] + " " + col2[i] + ".";i++;
make the multi-assignments consistent by using ternary operator.
int i = 0;
String content = "";
content+= (i==3?"and ":"") + col1[i]+" "+col2[i] + (i==3?".":", "); i++;
content+= (i==3?"and ":"") + col1[i]+" "+col2[i] + (i==3?".":", "); i++;
content+= (i==3?"and ":"") + col1[i]+" "+col2[i] + (i==3?".":", "); i++;
content+= (i==3?"and ":"") + col1[i]+" "+col2[i] + (i==3?".":", "); i++;
using while-loop to remove duplication.
int i = 0;
String content = "";
while(i<=3) {
content+= (i==3?"and ":"") + col1[i]+" "+col2[i] + (i==3?".":", ");
i++;
}
replacing while-loop with for-loop.
String content = "";
for (int i = 0; i <= 3; i++) {
content+= (i==3?"and ":"") + col1[i]+" "+col2[i] + (i==3?".":", ");
}
introduce variables to make the code more readable.
String content = "";
for (int i = 0; i <= 3; i++) {
String prefix = i == 3 ? "and " : "";
String current = col1[i] + " " + col2[i];
String suffix = i == 3 ? "." : ", ";
content += prefix + current + suffix;
}
inline the variables col1 & col2 that is used only once:
String content = "";
for (int i = 0; i <= 3; i++) {
String prefix = i == 3 ? "and " : "";
String current = roster[0][i] + " " + roster[1][i];
String suffix = i == 3 ? "." : ", ";
content += prefix + current + suffix;
}
replace magic number 3 with constant and the final code is below:
final int last = 3;
String content = "";
for (int i = 0; i <= last; i++) {
String prefix = i == last ? "and " : "";
String suffix = i == last ? "." : ", ";
String current = roster[0][i] + " " + roster[1][i];
content += prefix + current + suffix;
}
JOptionPane.showMessageDialog(null, "The student's names are: " + content);
StringBuilder message = new StringBuilder("The student's names are: ");
for (int i = 0; i < roster[0].length; i++) {
message
.append(roster[0][i])
.append(" ")
.append(roster[1][i]);
if (i < roster[0].length - 1)
message.append(", ");
if (i == roster[0].length - 2)
message.append("and ")
}
message.append(".");
JOptionPane.showMessageDialog(null, message.toString());
Possibly something like that. As you can see, you don't really save any lines, but obviously the code is more flexible as it can account for a variable length roster.
You can do the following: Initially assign the normal statement that you do not want repeated. Then loop through roster.
String rosterString= "The student's names are: ";
for(int i=0;i<= roster.length;i++){
for(int j=0;j<= roster[i].length;j++){
rosterString += (roster[i][j] + " ");
if (i == 1 && j < 2) {
rosterString += ", ";
}
else if (i == 1 && j == 2) {
rosterString += ", and";
}
else if (i == 1 && j == 3) {
rosterString += ".";
}
else {
rosterString += " ";
}
}
}
And then pass rosterString to your method.
String rosterString = "";
for(int i = 0; i < roster[0].length; i++) {
rosterString += roster[0][i] + " " + roster[1][i] + ", ";
}
That code will create a string with the names and commas. You could then add in if statements to check if it is near the end to change the , to an and or .
So my requirement is to display a message showing yours and your friend's initials in lower case (ie. "mf and js are friends").
Here's my code
String myFullName = "Daniel Camarena";
String friendsFullName = "John Smith";
System.out.println( myFullName.toLowerCase().charAt(0)
+ myFullName.toLowerCase().charAt(7)
+ " and "
+ friendsFullName.toLowerCase().charAt(0)
+ friendsFullName.toLowerCase().charAt(5)
+ " are friends." );
The output I get is
199 and js are friends.
myFullName.toLowerCase().charAt(0) + myFullName.toLowerCase().charAt(7)
are working on ascii integer value and hence 199
The reason strings addition works for the second name is because that is part of the string formed due to this:
+ " and "
Quick fix, add an empty string at start
System.out.println("" + myFullName.toLowerCase().charAt(0)
+ myFullName.toLowerCase().charAt(7)
+ " and "
+ friendsFullName.toLowerCase().charAt(0)
+ friendsFullName.toLowerCase().charAt(5)
+ " are friends." );
System.out.println( "" + myFullName.toLowerCase().charAt(0) + myFullName.toLowerCase().charAt(7)
+ " and "
+ friendsFullName.toLowerCase().charAt(0)
+ friendsFullName.toLowerCase().charAt(5)
+ " are friends." );
Append the blank string to convert it to String and then it will start doing concanetation . As '+' is overloaded operator it is doing addition till it encounters String.
You can use following code :
String myFullName = "Daniel Camarena";
String friendsFullName = "John Smith";
String[] arrMyFullName = myFullName.toLowerCase().split(" ");
String[] arrFriendsFullName = friendsFullName.toLowerCase().split(" ");
String message = "";
for(String s : arrMyFullName)
message += s.charAt(0);
message += " and ";
for(String s : arrFriendsFullName)
message += s.charAt(0);
message += " are friends.";
System.out.println( message );
Above code also work if name is more than 2 words.
Try:
System.out.println( "" + myFullName.toLowerCase().charAt(0)
+ myFullName.toLowerCase().charAt(7)
+ " and "
+ friendsFullName.toLowerCase().charAt(0)
+ friendsFullName.toLowerCase().charAt(5)
+ " are friends." );
With this one you can have any name of friends. Instead of correcting the index which differs for each name.
String myFullName = "Daniel Camarena";
String friendsFullName = "John Smith";
String[] myNameSplit = myFullName.split(" ");
String myFirstInitial = String.valueOf(myNameSplit[0].charAt(0));
String myLastInitial = String.valueOf(myNameSplit[1].charAt(0));
String[] myFriendNameSplit = friendsFullName.split(" ");
String myFriendFirstInitial = String.valueOf(myFriendNameSplit[0].charAt(0));
String myFriendLastInitial = String.valueOf(myFriendNameSplit[1].charAt(0));
System.out.println(myFirstInitial+myLastInitial + " and " + myFriendFirstInitial+myFriendLastInitial+ " are friends");
It is adding ASCII value of d and c in output to avoid that do as following.
String myFullName = "Daniel Camarena";
String friendsFullName = "John Smith";
System.out.println( myFullName.toLowerCase().charAt(0)
+""+ myFullName.toLowerCase().charAt(7)
+ " and "
+ friendsFullName.toLowerCase().charAt(0)
+ friendsFullName.toLowerCase().charAt(5)
+ " are friends." );
I'm starting with this String:
"NAME-RAHUL KUMAR CHOUDHARY ADDRESS-RAJDHANWAR DISTRICT-GIRIDIH STATE-JHARKHAND PIN CODE-825412"
I want to split the name and address, and print it like this:
NAME:RAHUL KUMAR CHOUDHARY , DDRESS-RAJDHANWAR DISTRICT-GIRIDIH STATE-JHARKHAND PIN CODE-825412. like this
This is what I have so far:
String str_colArow3 = colArow3.getContents();
//Display the cell contents
System.out.println("Contents of cell Col A Row 3: \""+str_colArow3 + "\"");
if(str_colArow3.contains("NAME"))
{
}
else if(str_colArow3.contains("ADDRESS"))
{
}
String string = "NAME-RAHUL KUMAR CHOUDHARY ADDRESS-RAJDHANWAR DISTRICT-GIRIDIH STATE-JHARKHAND PIN CODE-825412";
String[] parts = string.split("-");
string = "Name: " + parts[1].substring(0, parts[1].length() - 7)
+ "\nAdress: " + parts[2] + " - " + parts[3]
+ "\nPin Code: " + parts[5];
Something like this. Check out the split() method for strings, your string is a bit poorly formatted to use this, though. You have to adjust for your own needs.
Edit: Better way to do this, with different string input.
String string = "RAHUL KUMAR CHOUDHARY:RAJDHANWAR:GIRIDIH:JHARKHAND:825412";
String[] parts = string.split(":");
string = "Name: " + parts[0] + "\n"
+ "Address: " + parts[1] + "\n"
+ "District: " + parts[2] + "\n"
+ "State: " + parts[3] + "\n"
+ "Pin Code: " + parts[4] + "\n";