I have a String of the form "Firstname MiddleInitial Lastname".
I want to convert it to "Lastname, Firstname MiddleIntial"
Some names may have middle initial, but some may not:
String Name1 = "John Papa P";
String name2 = "Michael Jackson";
// Desired Output
result1 = "Papa, John P";
result2 = "Jackson, Michael";
How can I accomplish this?
Maybe something like this?
public class HelloWorld{
public static void main(String []args){
String name1 = "John Papa P";
String name2 = "Michael Jackson";
String[] split = name1.split(" ");
String result;
if (split.length > 2) {
result = split[1] + ", " + split[0] + " " + split[2];
} else {
result = split[1] + ", " + split[0];
}
System.out.println(result);
}
}
You can use the split() method on your String to split it into an array of Strings using a space as a delimiter, and rearrange the array as necessary.
A possible way to do this is using split function and make it into lists.
String one = "John Doe";
String two = "Albert Einstein";
String [] onelst = one.split(" ");
String [] twolst = two.split(" ");
String oneMod = onelst[1]+" "+onelst[0];
String twoMod = twolst[1]+" "+twolst[0];
System.out.println(oneMod);
System.out.println(twoMod);
Output for this:
Doe John
Einstein Albert
Just use split() to create an array of names. Now just use size() to get the size of the array, if it's 3 you have MiddleInitial, if 2 you dont.
Then for each case rearrange the array as you want.
Related
I get in put string as below
{key: IsReprint, value:COPY};{key: IsCancelled, value:CANCELLED}
I want to convert above string as below in my output...,want to add quotes to the string (key , value pairs).
{"key": "IsReprint", "value":"COPY"};{"key": "IsCancelled", "value":"CANCELLED"}
Please assist..thanks in advance..
String input="{key: IsReprint, value:COPY};{key: IsCancelled,value:CANCELLED}";
if(input.contains("key:") && input.contains("value:") ){
input=input.replaceAll("key", "\"key\"");
input=input.replaceAll("value", "\"value\"");
input=input.replaceAll(":", ":\"");
input=input.replaceAll("}", "\"}");
input=input.replaceAll(",", "\",");
//System.out.println("OUTPUT----> "+input);
}
I above code has problem if input string as below
{key: BDTV, value:Africa Ltd | Reg No: 433323240833-C23441,GffBLAB | VAT No: 4746660239035Level 6}
You could use regex to accomplish the same, but more concisely:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JsonScanner {
private final static String JSON_REGEX = "\\{key: (.*?), value:(.*?)(\\};|\\}$)";
/**
* Splits the JSON string into key/value tokens.
*
* #param json the JSON string to format
* #return the formatted JSON string
*/
private String findMatched(String json) {
Pattern p = Pattern.compile(JSON_REGEX);
Matcher m = p.matcher(json);
StringBuilder result = new StringBuilder();
while (m.find()) {
result.append("\"key\"=\"" + m.group(1) + "\", ");
result.append("\"value\"=\"" + m.group(2) + "\" ; ");
System.out.println("m.group(1)=" + m.group(1) + " ");
System.out.println("m.group(2)=" + m.group(2) + " ");
System.out.println("m.group(3)=" + m.group(3) + "\n");
}
return result.toString();
}
public static void main(String... args) {
JsonScanner jsonScanner = new JsonScanner();
String result = jsonScanner.findMatched("{key: TVREG, value:WestAfrica Ltd | VAT No: 1009034324829/{834324}<br/>Plot No.56634773,Road};{key: REGISTRATION, value:SouthAfricaLtd | VAT No: 1009034324829/{834324}<br />Plot No. 56634773, Road}");
System.out.println(result);
}
}
You might have to tweak the regex or output string to meet your exact requirements, but this should give you an idea of how to get started...
You have to escape characters
How do I escape a string in Java?
For example:
String s = "{\"key\": \"IsReprint\""; // will be print as {"key": "IsReprint"
The double quote character has to be escaped with a backslash in a Java string literal. Other characters that need special treatment include:
Carriage return and newline: "\r" and "\n"
Backslash: "\"
Single quote: "\'"
Horizontal tab and form feed: "\t" and "\f".
Here is a solution using a regexp to split your input into key / value pairs and then aggregating the result using the format you wish :
// Split key value pairs
final String regexp = "\\{(.*?)\\}";
final Pattern p = Pattern.compile(regexp);
final Matcher m = p.matcher(input);
final List<String[]> keyValuePairs = new ArrayList<>();
while (m.find())
{
final String[] keyValue = input.substring(m.start() + 1, m.end() - 1) // "key: IsReprint, value:COPY"
.substring(5) // "IsReprint, value:COPY"
.split(", value:"); // ["IsReprint", "COPY"]
keyValuePairs.add(keyValue);
}
// Aggregate
final List<String> newKeyValuePairs = keyValuePairs.stream().map(keyValue ->
{
return "{\"key\": \"" + keyValue[0] + "\", \"value\":\"" + keyValue[1] + "\"}";
}).collect(Collectors.toList());
System.out.println(StringUtils.join(newKeyValuePairs.toArray(), ";"));
The result for the folowing input string
final String input = "{key: IsReprint, value:COPY};{key: IsCancelled, value:CANCELLED};{key: BDTV, value:Africa Ltd | Reg No: 433323240833-C23441,GffBLAB | VAT No: 4746660239035<br />Level 6}";
is {"key": "IsReprint", "value":"COPY"};{"key": "IsCancelled", "value":"CANCELLED"};{"key": "BDTV", "value":"Africa Ltd | Reg No: 433323240833-C23441,GffBLAB | VAT No: 4746660239035<br />Level 6"}
This gives the exact result as you want!
public static void main(String s[]){
String test = "{key: TVREG, value:WestAfrica Ltd | VAT No: 1009034324829/{834324}<br />Plot No. 56634773, Road};{key: REGISTRATION, value:SouthAfricaLtd | VAT No: 1009034324829/{834324}<br />Plot No. 56634773, Road}";
StringBuilder sb= new StringBuilder();
String[] keyValOld = test.split(";");
for(int j=0; j<keyValOld.length; j++){
String keyVal = keyValOld[j].substring(1,keyValOld[j].length()-1);
String[] parts = keyVal.split("(:)|(,)",4);
sb.append("{");
for (int i = 0; i < parts.length; i += 2) {
sb.append("\""+parts[i].trim()+"\": \""+parts[i + 1].trim()+"\"");
if(i+2<parts.length) sb.append(", ");
}
sb.append("};");
}
System.out.println(sb.toString());
}
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NewClass {
public static void main(String[] args) {
String input="{key: IsReprint, value:COPY};{key: IsCancelled, value:CANCELLED};{key: BDTV,value:Africa Ltd | Reg No: 433323240833-C23441,GffBLAB | VAT No: 4746660239035 Level 6}";
Matcher m1 = Pattern.compile("key:" + "(.*?)" + ",\\s*value:").matcher(input);
Matcher m2 = Pattern.compile("value:" + "(.*?)" + "}").matcher(input);
StringBuilder sb = new StringBuilder();
while(m1.find() && m2.find()){
sb.append("{\"key\": ")
.append("\"")
.append(m1.group(1).trim())
.append("\", \"value\":")
.append("\"")
.append(m2.group(1).trim())
.append("\"};");
}
String output = sb.deleteCharAt(sb.length()-1).toString();
System.out.println(output);
}
}
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
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.
I have the following data which is stored as a big string.
"John Chips Monday \n"
"Tom Pizza Tuesday\n"
"Jerry IceCream Wednesday\n"
"Jennifer Coffee Thursday\n"
Now I wish to split this string so I can get individual data from this string and place each data in an array for example.
each element of names array stores the names seen above like names[0] = john, names[1] = Tom etc.
each element of food array stores the foods seen above like food[0] = chips, food[1] = pizza.
I have tried doing this
John + "\t" + Chips + "-" + Monday + "\n"
Tom + "\t" + Pizza + "-" + Tuesday+ "\n"
Jerry + "\t" + IceCream + "-" + Wednesday+ "\n"
Jennifer + "\t" + Coffee + "-" + Thursday+ "\n"
String nameCol[] = data.split("\\t");
String foodCol[] = data.split("-");
The output I get is nearly there but wrong as it contains data that I don't want in the array for example the output for first array is
nameCol[0] = John
nameCol[1] = Chips -
nameCol[2] = Monday
Element 0 contains john but the other elements contain the parts I don't want.
I tried for a limit but this did not work
String nameCol[] = data.split("\\t",1);
String foodCol[] = data.split("-",1);
This will work:
String yourLine = "John Chips Monday\n"; // Read your line in here
String[] resultCol = yourLine.split(" ");
resultCol[2] = resultCol[2].split("\\n")[0];
System.out.println( resultCol[2] );
The first split on the string will give you "John", "Chips" and "Monday\n". The second split takes "Monday\n" from the array and splits it. Returning "Monday" back into the final index of the array resultCol[2]. From here you can simply assign each element in the array to the arrays you require.
Don't use them separately, use the delimiters together, like : String dataArr\[\] = data.split("\t\n",1);
Then iterate through the String[]:
for (int i = 0; i < dataArr.length; i+=2) {
String name = dataArr[i];
String food = dataArr[i+1];
// ... do whatever you want with them.
}
Or, you could also try the similar Pattern-Matcher approach
You should:
use Lists for each column, (Lists can increase their size dynamically, while arrays have fixed size)
iterate over each line,
split it on whitespace (or any separator you are using)
and add column[0] to list of names, column[1] to list of food and so on with other columns.
OR if you know that each line has only three words you could simply use Scanner and iterate over words instead of lines with split.
while(scanner.hasNext()){
listOfNames.add(scanner.next());
listOfFood.add(scanner.next());
listOfDays.add(scanner.next());
}
Try this,
String str="John" + "\t" + "Chips" + "\t" + "Monday" + "-" + "Test"+"\n"+"chet";
String st1= str.replaceAll("(\\t)|(-)|(\n)"," ");
String []st=st1.split(" ");
for(String s : st)
System.out.println(s);
From your data, I assume that you are reading this values from a files. If you know how many lines there are, you could use 3 arrays, each for every type of data that needs to be retrived. If you don't know the size, you could go with 3 ArrayLists. Your problem is that after making the split, you didn't put them in the correct arrays. The following code assumes that you already have all the data in one String.
final String values[] = data.split("\\n");
final ArrayList<String> names = new ArrayList<String>();
final ArrayList<String> foods = new ArrayList<String>();
final ArrayList<String> days = new ArrayList<String>();
for (String line : values) {
String[] split = line.trim().split("[ ]+");
names.add(split[0]);
foods.add(split[1]);
days.add(split[2]);
}
Another thing that you must consider is to check if the data always has 3 values on a "line", or else further error checking is needed.
If your string is always going to be "[name] [food] [day]", then you could do:
String[] names = new String[allData.length]; //A list of names
String[] food = new String[allData.length]; //A list of food
String[] day = new String[allData.length]; //A list of days
for(int i = 0 ; i < allData.length ; i++)
{
String[] contents = allData[i].split(" "); //Or use a similar delimiter.
names[i] = contents[0];
food[i] = contents[1];
day[i] = contents[2];
}
Try this code
String s = "John Chips Monday \n Tom Pizza Tuesday \n Jerry IceCream Wednesday \n Jennifer Coffee Thursday \n";
String split[] = s.split("\n");
String names[] = new String[split.length];
String foods[] = new String[split.length];
String days[] = new String[split.length];
for (int i = 0; i < split.length; i++) {
String split1[] = split[i].trim().split(" ");
names[i]=split1[0];
foods[i]=split1[1];
days[i]=split1[2];
System.out.println("name=" + names[i] + ",food=" + foods[i] + ",day=" + days[i]);
}
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];
}
}