Change order of words Java - java

I cannot figure out how to change the order of a given name.
For example: Van-Dame Claud
Result: Claud Dame-Van
I created this method, but it seems that is not correct, any suggestion or maybe a better method?
public String NameInvers(){
String Name, Name = null, Name = null, NameFinal;
int s1 = getName().indexOf(' ');
int s2 = getName().indexOf('-');
if(s1 != 0){
Name1 = getName().substring(0, s1);
if(s2 != 0)
{
Name2 = getName().substring(s1, s2);
Name3 = getName().substring(s2);
}
NameFinal = Name3 + Name2 + Name1;
}
else
NameFinal = getName();
return NameFinal;
}
Edit: In my Main method I have a number of names. The thing is that it says: throw new StringIndexOutOfBoundsException(subLen) and it won't show up.

Here you go:
public static String reverseName (String name) {
name = name.trim();
StringBuilder reversedNameBuilder = new StringBuilder();
StringBuilder subNameBuilder = new StringBuilder();
for (int i = 0; i < name.length(); i++) {
char currentChar = name.charAt(i);
if (currentChar != ' ' && currentChar != '-') {
subNameBuilder.append(currentChar);
} else {
reversedNameBuilder.insert(0, currentChar + subNameBuilder.toString());
subNameBuilder.setLength(0);
}
}
return reversedNameBuilder.insert(0, subNameBuilder.toString()).toString();
}
Test:
public static void main(String[] args) {
printTest("Van-Dame Claud");
printTest("Victor Hugo");
printTest("Anna");
printTest("");
}
private static void printTest(String S) {
System.out.printf("Reverse name for %s: %s\n", S, reverseName(S));
}
Output:
Reverse name for Van-Dame Claud: Claud Dame-Van
Reverse name for Victor Hugo: Hugo Victor
Reverse name for Anna: Anna
Reverse name for :

First of all, you duplicate your variable Name declaration, three times. I suppose that you want to put:
String Name1, Name2 = null, Name3 = null, NameFinal;
instead of:
String Name, Name = null, Name = null, NameFinal;
Then, if you just have 2 names with a - in the middle and you want to change their order you can use split function to separate it, finding where - is. You can use it like this:
String string = "Van-Dame Claud";
String[] divide = string.split("-");
String Name1 = divide[0];
String Name2 = divide[1];
String result = Name2 + "-" + Name1;
EDIT: Name1 will be Van and Name2 will be Dame Claud so the result will be Dame Cloud-Van.
I expect it works for you!

You want to have a method to convert all names or just the the names in form of Name-Name Name? I'm assuming you want a method for all names. Since if you just want to reverse names in this specific form, there is no meaning for you to check value of s1 and s2, you know s1 and s2 must be a positive number. If you check because you want to do error checking, then you should throw an exception if the name is not in the form you want. If you want to do it for all names, below is the pseudocode, you can implement it yourself (your code contains several errors, you are using Name1, Name2, Name3, but you never declared them and duplicate variable Name declaration):
string finalName = ""
string [] strs1 = name split by " "
foreach str1 in strs1
string [] strs2 = str1 split by "-"
foreach str2 in strs2
if str2.first?
finalName = str2 + " " + finalName
else
finalName = str2 + "-" + finalName
end
end
end
return finalName.substring 0, finalName.length-1 //remove the space at the end
I think this would work. Hope you find it useful.

Related

Splitting Full Name

I have string for instance, "John Daws Black" splitted with spaces and I need to split them to two parts so that there will be name part like "John Daws" and surname part like "Black". However the front name part can be any length like "John Erich Daws Black". My code can get the last part:
public String getSurname(String fullName){
String part = "";
for (String retval: fullName.split(" "))
part = retval;
return part;
}
But I don't know how to get the front part.
Just find the last space, then manually split there using substring().
String fullName = "John Erich Daws Black";
int idx = fullName.lastIndexOf(' ');
if (idx == -1)
throw new IllegalArgumentException("Only a single name: " + fullName);
String firstName = fullName.substring(0, idx);
String lastName = fullName.substring(idx + 1);
Try this.
public String getName(String fullName){
return fullName.split(" (?!.* )")[0];
}
public String getSurname(String fullName){
return fullName.split(" (?!.* )")[1];
}
Below methods worked for me. It takes into account that if middle name is present, then that gets included in first name:
private static String getFirstName(String fullName) {
int index = fullName.lastIndexOf(" ");
if (index > -1) {
return fullName.substring(0, index);
}
return fullName;
}
private static String getLastName(String fullName) {
int index = fullName.lastIndexOf(" ");
if (index > -1) {
return fullName.substring(index + 1 , fullName.length());
}
return "";
}
Get the last element of the array after spliting it:
String fullName= "John Daws Black";
String surName=fullName.split(" ")[fullName.split(" ").length-1];
System.out.println(surName);
Output:
Black
Edit:
for the front part, use substring:
String fullName= "John Daws Black";
String surName=fullName.split(" ")[fullName.split(" ").length-1];
String firstName = fullName.substring(0, fullName.length() - surName.length());
System.out.println(firstName );
Output:
John Daws
//Split all data by any size whitespace
final Pattern whiteSpacePattern = Pattern.compile("\\s+");
final List<String> splitData = whiteSpacePattern.splitAsStream(inputData)
.collect(Collectors.toList());
//Create output where first part is everything but the last element
if(splitData.size() > 1){
final int lastElementIndex = splitData.size() - 1;
//connect all names excluding the last one
final String firstPart = IntStream.range(0,lastElementIndex).
.mapToObj(splitData::get)
.collect(Collectors.joining(" "));
final String result = String.join(" ",firstPart,
splitData.get(lastElementIndex));
}
Just a re-write for Andreas answer above but using sperate methods to get first and last name
public static String get_first_name(String full_name)
{
int last_space_index = full_name.lastIndexOf(' ');
if (last_space_index == -1) // single name
return full_name;
else
return full_name.substring(0, last_space_index);
}
public static String get_last_name(String full_name)
{
int last_space_index = full_name.lastIndexOf(' ');
if (last_space_index == -1) // single name
return null;
else
return full_name.substring(last_space_index + 1);
}
Here's a solution I've used before that accounts for suffixes too.. ( 3 chars at the end )
/**
* Get First and Last Name : Convenience Method to Extract the First and Last Name.
*
* #param fullName
*
* #return Map with the first and last names.
*/
public static Map<String, String> getFirstAndLastName(String fullName) {
Map<String, String> firstAndLastName = new HashMap<>();
if (StringUtils.isEmpty(fullName)) {
throw new RuntimeException("Name Cannot Be Empty.");
}
String[] nameParts = fullName.trim().split(" ");
/*
* Remove Name Suffixes.
*/
if (nameParts.length > 2 && nameParts[nameParts.length - 1].length() <= 3) {
nameParts = Arrays.copyOf(nameParts, nameParts.length - 1);
}
if (nameParts.length == 2) {
firstAndLastName.put("firstName", nameParts[0]);
firstAndLastName.put("lastName", nameParts[1]);
}
if (nameParts.length > 2) {
firstAndLastName.put("firstName", nameParts[0]);
firstAndLastName.put("lastName", nameParts[nameParts.length - 1]);
}
return firstAndLastName;
}
Try this :
String[] name = fullname.split(" ")
if(name.size > 1){
surName = name[name.length - 1]
for (element=0; element<(name.length - 1); element++){
if (element == (name.length - 1))
firstName = firstName+name[element]
else
firstName = firstName+name[element]+" "
}
}
else
firstName = name[0]

Use for loop to fill the fields

so first here is my code :
public class eol {
public static void main(String[] args) {
String x = "Charles.Baudelaire*05051988*France Sergei.Esenin*01011968*Russia Herman.Hesse*23051996*Germany";
String[] word= x.split("[.,*, ]");
for(int i=0;i<word.length;i++){
// System.out.print(word[i]+" ");
}
String name = word[0];
String lastname = word[1];
String dod =word[2];
String cob= word[3];
System.out.print("First person data : "+
"\n"+ name +" "+ "\n"+lastname+" "+"\n"+ dod+" "+"\n"+ cob);
I want to loop through string x, and take needed values, and use them to make 3 objects of class writer, is there any way i do this with for loop ?
Or would i have to "break" original string in 3 smaller arrays, then do for loop for every one of them.
I mean, i can use for loop to print out data on screen, by incrementing counter by certain value, how ever to add these data to fields is something I don't understand how to do.
Sure. You can do the following:
Validate.isTrue(word.length % 4 == 0, "Array size must be a multiple of 4");
List<Writer> writers = new ArrayList<>();
for (int i=0; i<word.length; i+=4) {
String name = word[i];
String lastname = word[i+1];
String dod =word[i+2];
String cob= word[i+3];
writers.add(new Writer(name, lastname, dod, cob));
}
i += 4 instead of i++ after each tern of loop, and use word[i], word[i+1], word[i+2] and word[i+3] in loop.
i.e.
String x = "Charles.Baudelaire*05051988*France Sergei.Esenin*01011968*Russia Herman.Hesse*23051996*Germany";
String[] word= x.split("[.,*, ]");
for(int i=0;i<word.length;i+=4){
String name = word[i];
String lastname = word[i+1];
String dod =word[i+2];
String cob= word[i+3];
// Use these variable.
}

How to create a string from many strings efficiently in Java

In a Java code, I have 11 different strings, some of them (at most 9) can be null. Strings are a part of an object. If none of them is null, I make a string like this :
string1 + "," + string2 + "," + string3 + "," + string4 + "," + string5 + "," + string6 + "(" + string7 + ")" + string8 + string9 + "+" + string10 + string11
If none of them is null, it's okey. But some of them can be null. If I check if each of them is null, code gets really slow and long. How can I generate such a string in an efficient and fast way? Thanks.
public static void main(String[] args) {
String string1 = "test1";
String string2 = "test2";
String string3 = "test3";
String string4 = null;
String string5 = "test5";
StringBuilder stringBuilder = new StringBuilder();
List<String> valueList = new ArrayList<>();
valueList.add(string1);
valueList.add(string2);
valueList.add(string3);
valueList.add(string4);
valueList.add(string5);
// etc.
for (String value : valueList) {
if (value != null) {
stringBuilder.append(value);
}
else {
value = ",";
stringBuilder.append(value);
}
}
System.out.println(stringBuilder);
}
Output :
test1test2test3,test5
With Java 8 you could use this for the first part with comma-delimited strings:
String part1 = Stream.of(string1, string2, string3, string4, string5, string6)
.filter(Objects.notNull())
.collect(joining(",");
From then on you have an irregular structure so you'll need custom logic to handle it. The helper function
static String emptyForNull(String s) {
return s == null ? "" : s;
}
can get you part of the way.
In Java 8, you can stream and join with Collectors, and filter with Objects classes
List<String> strings = Arrays.asList("first", "second", null, "third", null, null, "fourth");
String res = strings.stream().filter(Objects::nonNull).collect(Collectors.joining(","));
System.out.println(res);
results in output
first,second,third,fourth
If you simply want your code to be as short as possible, use String.format and get rid of the "null" in the string.
String result = String.format("%s,%s,%s,%s,%s,%s(%s)%s,%s,%s,%s",
string1, string2, string3, string4, string5,
string6, string7, string8, string9, string10,
string11);
System.out.println(result.replace("null", ""));
If 6th index of your string is always surrounded by ( and ) then you can use following code.
List<String> vals = new ArrayList<>();
vals.add(string1);
vals.add(string2);
vals.add(string3);
vals.add(string4);
vals.add(string5);
vals.add(string6);
vals.add(string7);
vals.add(string8);
vals.add(string9);
vals.add(string10);
vals.add(string11);
for (int i =0 ; i < vals.size(); i++) {
// check null values
if (vals.get(i) != null) {
// as your requirement surround 7th value with ( and )
if(vals.indexOf(vals.get(i)) == 6) {
values += "\b(" + vals.get(i)+")";
} else {
values += vals.get(i)+",";
}
}
}
System.out.println(values+"\b");
Output
if 4th and 9th strings are null then,
test1,test2,test3,test5,test6(test7)test8,test10,test11

Check if a substring contains a certain value

Is it possible to check if a substring contains a certain value and do something? I have this piece of code i'm wondering if I could check if desc: contains the value \n I have the config made with the following information
test: desc:\ndog\ntest
test2: desc:\ndog3
So how would I be able to retrieve the \n and loop through all the \n in that specific string list and do a action.
for (String s : plugin.file.getFile().getStringList(plugin.file.path))
{
public void substring(){
String labels = "item: desc:";
String[] parts = labels.split(" ");
String part1 = parts[0];
String part2 = parts[1];
System.out.println("Desc Value: " + s.substring(part2.length()).split(" ")[1])
}
}
I don't understand your question in full but I think that you want something like this:
String test = "desc:\ndog\ntest";
String test1 = "desc:\ndog3";
String[] parts = test.split(":");
String name = parts[0];
String[] values = parts[1].trim().split("\n");
System.out.println("Name: " + name);
for (int i = 0; i<values.length; i++)
{
System.out.println(values[i]);
}
You just split the values of [1] index in that parts table.

error related to array index

Below code has variable "name". This may contain first and last name or only first name. This code checks if there is any white space in variable "name". If space exists, then it splits.
However, I am getting the "Error : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at Space.main(Space.java:9)" during below cases
If there is a white space before "Richard"
If there is a white space after "Richard" without second word or second string.
If I have two spaces after "Richard" then it will not save the name in lname variable.
How to resolve this error.
public class Space {
public static void main(String[] args) {
String name = "Richard rinse ";
if(name.indexOf(' ') >= 0) {
String[] temp;
temp = name.split(" ");
String fname = temp[0];
String lname = temp[1];
System.out.println(fname);
System.out.println(lname);
} else {
System.out.println("Space does not exists");}
}
}
you have to split a string using "\s" like this
name.split("\\s+");
If there are two spaces temp[1] will be empty, given "Richard rinse" the array is split this way
1 Richard
2
3 rinse
You should trim() the string and do something like
while(name.contains(" "))
name=name.replace(" "," ");
String[] parts = name.trim().split("\\s+");
if (parts.length == 2) {
// print names out
} else {
// either less than 2 names or more than 2 names
}
trim removes leading and trailing whitespace as this lead to either leading or trailing empty strings in the array
the token to split on is a regular expression meaning any series of characters made up of one or more whitespace characters (space, tabs, etc...).
Maybe that way:
public class Space {
public static void main(String[] args) {
String name = "Richard rinse ";
String tname = name.trim().replace("/(\\s\\s+)/g", " ");
String[] temp;
temp = name.split(" ");
String fname = (temp.length > 0) ? temp[0] : null;
String lname = (temp.length > 1) ? temp[1] : null;
if (fname != null) System.out.println(fname);
if (lname != null) System.out.println(lname);
} else {
System.out.println("Space does not exists");
}
}
To trim the white spaces, use this.
public String trimSpaces(String s){
String str = "";
boolean spacesOmitted = false;
for (int i=0; i<s.length; i++){
char ch = s.chatAt(i);
if (ch!=' '){
spacesOmitted = true;
}
if (spacesOmitted){
str+=ch;
}
}
return str;
}
Then use the trimmed string in the place of name.

Categories

Resources