Separating firstname and lastname using lastIndexof() in String class [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have written a code which separates first name and last name in a name String:
public class NameSeperator {
public static void main(String[] args)
{
String custName="Your Name";
int index;
String firstName;
index=custName.indexOf(" ");
**int last=custName.lastIndexOf("")**;
firstName=custName.substring(0,index);
String lastName=custName.substring(index+1,last);
// get the first name
System.out.println("First Name = "+firstName);
System.out.println("Last Name = "+lastName);
}
}
I have used
int last=custName.lastIndexOf("")
and used only "" here but it takes complete string here.Is "" means the complete string at which a particular string method is called?

You can directly split it by space and then use array index
String name[] = custName.split(" ");
String firstName = name[0];
String lastName = name[1]

I would recommend this simplified version :
int index = custName.indexOf(' ');
String firstName = custName.substring(0, index);
String lastName = custName.substring(index + 1);
Note that indexOf searches for a single character. Also the second substring for lastName gets the remaining chars until the end.

Modify your code :
String custName="Your Name";
int start = custName.indexOf(' ');
int end = custName.lastIndexOf(' ');
String firstName = "";
String middleName = "";
String lastName = "";
if (start >= 0) {
firstName = custName.substring(0, start);
if (end > start)
middleName = custName.substring(start + 1, end);
lastName = custName.substring(end + 1, custName.length());
}
System.out.println("First Name = "+firstName);
System.out.println("Middle Name = "+middleName);
System.out.println("Last Name = "+lastName);

Related

Creating dialog windows

I'm trying to create a dialog window where I ask for a persons name with the format: Lastname, Surname
I'm then trying to show just the surname name in a new dialog window with the format: Hello! SURNAME!
This is my code so far:
import javax.swing.*;
public class Surname {
public static void main(String[] arg) {
String a = JOptionPane.showInputDialog(null, "Write your name: Lastname, surname ");
int i, j;
i = a.lastIndexOf(???);
j = a.indexOf(',' + 1);
a = a.substring(i, j);
JOptionPane.showMessageDialog(null, "Hello! " + a.toUpperCase()); }}
Your substring is not correct, for the start you'll need the index of the comma, for the end simply the length of the string:
int i, j;
i = a.indexOf(',') + 2;
j = a.length();
a = a.substring(i, j);
You can extract the surname by splitting the string by ", ".
For example
String surname = "Novovic, Felix".split(", ")[0];
Since we are accessing an array here which size is fully determined by the input of the user, i.e. the user inputs "Novovic, Felix, Hello, World" you should reassure that the input is in the correct format before you access the array.
For example, by checking that the array length = 2
Using split() this will do:
public static void main(String[] args) {
String a = JOptionPane.showInputDialog(null, "Write your name: Lastname, surname ");
String[] nameParts = a.split(",");
JOptionPane.showMessageDialog(null, "Hello! " + nameParts[1].trim().toUpperCase());
}
... but you would probably want to add some more error handling. So this is only a bare bone example

How do I get the program to accept a surname of less than 5 characters?

How do I get the program to accept a surname less than 5 characters for example joe cole would be jcole.
public void names(String firstName, String surname) {
String userIdentity = firstName.substring(0,1) + surname.substring(0,5);
System.out.println(userIdentity.toLowerCase());
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
UserId name = new UserId();
String first;
String last;
System.out.println("Enter first name: ");
first = scan.next();
System.out.println("Enter surname: ");
last = scan.next();
name.names(first, last);
scan.close();
}
You can use Math.min(int, int) to get the lesser value of 5 and the surname.length(). Something like,
public void names(String firstName, String surname) {
String userIdentity = firstName.substring(0,1) //
+ surname.substring(0, Math.min(surname.length(), 5));
System.out.println(userIdentity.toLowerCase());
}
Instead of
String userIdentity = firstName.substring(0,1) + surname.substring(0,5);
Only create a substring if the name is long enough.
String userIdentity = firstName.substring(0,1) +
surname.substring(0,(surname.length >= 5) ? 5 : surname.length);

Getting the full name from a user

public class Test {
public static void main(String[] args) {
String name = "John King IV. Cena";
int start = name.indexOf(' ');
int end = name.lastIndexOf(' ');
String firstName = "";
String middleName = "";
String lastName = "";
if (start >= 0) {
firstName = name.substring(0, start);
if (end > start)
middleName = name.substring(start + 1, end);
lastName = name.substring(end + 1, name.length());
}
System.out.println(firstName);
System.out.println(middleName);
System.out.println(lastName);
}
}
In above code I dont want middle name. I want to get full name from user then it has to split like firstname and lastname.
You can try String'ssplit method to do this:
String name = "John King IV. Cena";
String []nameArray=name.split("\\s+");
System.out.println("FirstName "+nameArray[0] );
System.out.println("LastName "+nameArray[nameArray.length-1]);

ReplaceAll and Regular Expression

I am trying to insert tuples into newly created tables of a database schema I am building for SQL.
The issue is, I am to expect the first line to be
ssn INTEGER(9), cname VARCHAR(25), gender VARCHAR(6), age VARCHAR(3), profession VARCHAR(25)
But I want it to just be this:
ssn, cname, gender, age, profession
The previous method I tried with two splits, one for the space and the other for the comma is not working, so I thought using replace all would be easier. However, I am not sure what to try for the regular expression. How should these be created?
private static String parseFile (String[] x, Connection conn,
String tableName) {
// assume the first line is the relation name layout
String query = "INSERT INTO " + tableName;
String firstLine = x[0];
//System.out.println(firstLine);
String[] splits = firstLine.split(" ");
String[] finalSplit = new String[50];
String finalString = "";
for (int i=0; i<splits.length; i++) {
int counter = 0;
String[] split2 = splits[i].split(",");
//System.out.println (splits[i]);
for (int j=0; j<split2.length; j++) {
finalSplit[j+counter] = split2[j];
//System.out.println (split2[j]);
if (j%2 == 0)
finalString += split2[j];
counter += 1;
}
} // end outside for
System.out.println ("The attribute string is: " + finalString);
for (int i=1 ; i<x.length; i++)
{
String line = x[i];
String Final = query + " " + finalString + " " + line;
System.out.println ("Final string: " + Final);
}
return finalString;
}
I would appreciate a bit of guidance here.
EDIT:
Some of the output is:
The attribute string is: ssnINTEGER(9)cnameVARCHAR(25)genderVARCHAR(6)ageVARCHAR(3)professionVARCHAR(25)
Final string: INSERT INTO customer ssnINTEGER(9)cnameVARCHAR(25)genderVARCHAR(6)ageVARCHAR(3)professionVARCHAR(25) 3648993,Emily,male,63,Consulting
Final string: INSERT INTO customer ssnINTEGER(9)cnameVARCHAR(25)genderVARCHAR(6)ageVARCHAR(3)professionVARCHAR(25) 5022334,Barbara,male,26,Finance
Final string: INSERT INTO customer ssnINTEGER(9)cnameVARCHAR(25)genderVARCHAR(6)ageVARCHAR(3)professionVARCHAR(25) 1937686,Tao,female,5,IT
Some of the input of x is:
ssn INTEGER(9), cname VARCHAR(25), gender VARCHAR(6), age VARCHAR(3), profession VARCHAR(25)
3648993,Emily,male,63,Consulting
5022334,Barbara,male,26,Finance
1937686,Tao,female,5,IT
Try
firstLine.replaceAll(" [A-Z]+\\(\\d+\\)","");
Explanation: This regex finds words with 1 or more capital letters immediately followed by a left parenthesis, one or more digits, a right parenthesis and a comma.
replaceAll replaces all instances of this with an empty string.

String fullname Split java

I created a program which will parse the firstName, middleName and lastName. Here is the program and output. This program can definitely be improved and need some input on reducing my cumbersome ugly code and replace it with a better one. Any suggestions or example ?
public class Test {
public static void main(String[] args) {
String fullName = "John King IV. Cena";
String[] tokens = fullName.split(" ");
String firstName = "";
String middleName = "";
String lastName = "";
if(tokens.length > 0) {
firstName = tokens[0];
middleName = tokens.length > 2 ? getMiddleName(tokens) : "";
lastName = tokens[tokens.length -1];
}
System.out.println(firstName);
System.out.println(middleName);
System.out.println(lastName);
}
public static String getMiddleName(String[] middleName){
StringBuilder builder = new StringBuilder();
for (int i = 1; i < middleName.length-1; i++) {
builder.append(middleName[i] + " ");
}
return builder.toString();
}
}
John
King IV.
Cena
This code does the same, but doesn't keep a trailing space in the middle name. This is one of several possible cleaner implementations.
public class Test {
public static void main(String[] args) {
String name = "John King IV. Cena";
int start = name.indexOf(' ');
int end = name.lastIndexOf(' ');
String firstName = "";
String middleName = "";
String lastName = "";
if (start >= 0) {
firstName = name.substring(0, start);
if (end > start)
middleName = name.substring(start + 1, end);
lastName = name.substring(end + 1, name.length());
}
System.out.println(firstName);
System.out.println(middleName);
System.out.println(lastName);
}
}
As the guys said, next time go directly to https://codereview.stackexchange.com/
The algorithm will fail if the persons last name has more than one word, like Abraham Van Helsing. Van is not a middle name but part of the last name.
Obviously, there is no algorithm to clearly distinguish between middle name and last name in general. We always have to guess and we can only try to improve the probability that the guess is correct, maybe be checking middle name parts against word or filter lists.
You could also use a StringTokenizer for this:
import java.util.StringTokenizer;
public class Test {
public static void main(String[] args) {
String fullName = "John King IV. Cena";
StringTokenizer stok = new StringTokenizer(fullName);
String firstName = stok.nextToken();
StringBuilder middleName = new StringBuilder();
String lastName = stok.nextToken();
while (stok.hasMoreTokens())
{
middleName.append(lastName + " ");
lastName = stok.nextToken();
}
System.out.println(firstName);
System.out.println(middleName.toString().trim());
System.out.println(lastName);
}
}
Update the code to handle where there is no last name i.e. user enters only the first name like "Mark"
if(tokens.length > 0) {
firstName = tokens[0];
middleName = tokens.length > 2 ? getMiddleName(tokens) : "";
if(tokens.length > 1){
lastName = tokens[tokens.length -1];
}
}

Categories

Resources