What would be the best way to split this string directly after the CN= to store both the first and last name in separate fields as shown below?
String distinguisedName = "CN=Paul M. Sebula,OU=BBB,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=BBBBBB,DC=com"
String firstName"Paul"
String lastName="Sebula"
Don't re-invent the wheel. Assuming these are well-formed DN's, see the accepted answer on this question for how to parse without directly writing your own regex: Parsing the CN out of a certificate DN
Once you've extracted the CN, then you can apply some of the other parsing techniques suggested (use the Java StringTokenizer or the String.split() method as others here have suggested if it's known to be separated only by spaces). That assumes that you can make assumptions (eg. the first element in the resulting array is the firstName,the last element is the lastName and everything in between is middle names / initials) about the CN format.
You can use split:
String distinguisedName = "CN=Paul Sebula,OU=BAE,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=baesystems,DC=com";
String[] names = distinguisedName.split(",")[0].split("=")[1].split(" ");
String firstName = names[0];
String lastName= names.length > 2 ? names[names.length-1] : names[1];
System.out.println(firstName + " " + lastName);
See IDEONE demo, output: Paul Sebula.
This also accounts for just 2 names (first and last only). Note how last name is accessed it being the last item in the array.
public static void main(String[] args) {
String distinguisedName = "CN=Paul M. Sebula,OU=BBB,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=BBBBBB,DC=com";
String splitResult[]=distinguisedName.split(",")[0].split("=");
String resultTwo[]=splitResult[1].split("\\.");
String firstName=resultTwo[0].split(" ")[0].trim();
String lastName=resultTwo[1].trim();
System.out.println(firstName);
System.out.println(lastName);
}
output
Paul
Sebula
String distinguisedName = "CN=Paul M. Sebula,OU=BBB,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=BBBBBB,DC=com"
String[] commaSplit = distinguisedName.split(',');
String[] whitespaceSplit = commaSplit[0].split(' ');
String firstName = whitespaceSplit[0].substring(3);
String lastName = whiteSpaceSplit[2];
In steps:
String distinguisedName = "CN=Paul M. Sebula,OU=BBB,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=BBBBBB,DC=com";
String fullName = distinguisedName.substring(3, distinguisedName.indexOf(','));
String[] nameParts = fullName.split(" ");
String firstName = nameParts[0];
String lastName = nameParts[nameParts.length-1];
This will work for cases where the middle name/initial are not present as well.
Related
For example the name Donald trump (12 character) brings up the error string index out of range 7 (where the space is found) even though the name Donald trump is longer.
package test;
import javax.swing.JOptionPane;
public class Usernamesubstring {
public static void main(String[] args) {
String fullname = JOptionPane.showInputDialog("What is your full name");
int breakbetween = fullname.lastIndexOf(" ");
String firstnamess = fullname.substring(breakbetween - 3, breakbetween);
int length = fullname.length();
String lastnamess = fullname.substring(length - 3, length);
String firstnamec = firstnamess.substring(0, 0);
String lastnamec = lastnamess.substring(breakbetween + 1, breakbetween + 1 );
firstnamec = firstnamec.toUpperCase();
lastnamec = lastnamec.toUpperCase();
String firstname = firstnamess.substring(1,3);
String lastname = firstnamess.substring(1,3);
firstname = firstnamec + firstname;
lastname = lastnamec + lastname;
System.out.println(firstname + lastname);
}
}
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 7
at java.lang.String.substring(String.java:1963)
at test.Usernamesubstring.main(Usernamesubstring.java:14)
You've made it more complicated than it needs to be. A simple solution can be made using String.split (which divides a string into an array of smaller strings based on a delimiter, e.g. "Donald Trump".split(" ") == {"Donald", "Trump"})
Full Code
class Usernamesubstring // change that since it no longer uses substrings
{
public static void main (String[] args)
{
String fullName = "Donald Trump";
String[] parts = fullName.split(" ");
String firstName = parts[0]; // first item before the space
String lastName = parts[parts.length - 1]; // last item in the array
System.out.println(firstName + " " + lastName);
}
}
sometimes independent of your indexes
String fullName = "Donald Trump";
String[] result = fullName.split (" ");
in result you will find now
result [0] ==> Donald
result [1] ==> Trump
isn't that a little easier for your project?
Your error shoul be in the line String lastnamec = lastnamess.substring(breakbetween + 1, breakbetween + 1 ); as lastnamess is a string of lenght 3 from fullname.substring(length - 3, length); and breakbetween is greater then 3 for "Donald Trump", where space is character 6.
You should simpify your code a bit, it makes it easier to read and find the problems.
tl;dr: The exception occurs when you try to access a String at an index which exceeds it's length or is just not contained in the string (negative values).
Regarding your approach: It's usually not a good idea to prompt a name in full because people tend to input weird stuff or mix up the order. Better prompt for first and last name separately.
Assuming someone input his name with Firstname Lastname you wouldn't have to make such a substring mess, Java has some nice features:
String name = "Mario Peach Bowser";
name = name.trim();
String[] parts = name.split(" ");
String lastname = parts[parts.length-1];
String firstname = name.replace(lastname, "").trim();
System.out.println("Hello "+firstname+", your last name is: "+lastname);
In this case I am using the trim() function to remove whitespaces at the start and end and just split the string when a white space occurs. Since people can have some middle names and stuff, I just replace the last name out of the raw input string, call trim() on it again and you have everything extracted.
If you really want a substring approach, the following would work:
String lastname = name.substring(name.lastIndexOf(" ")).trim();
String firstname = name.substring(0,name.lastIndexOf(" ")).trim();
You usually don't store the index variables. But each variant would need some sort of error check, you can either use try{} and catch() or check the String before parsing.
Only these lines are required.
String[] nameArr = fullname.split(" ");
String lastN = nameArr[nameArr.length - 1];
int lastIndexOf = fullname.lastIndexOf(lastN);
String firstN = fullname.substring(0, lastIndexOf);
System.out.println(firstN + " " + lastN);
String str = "FirstName LastName - 1234xx"
In above case, want to replace above string with everything after " - " substring. In the above example it would mean changing str to 1234xx
The length of string after " - " is not fixed, hence cannot just capture last certain no. of characters
This approach gives FirstName LastName - - instead of desired output 1234xx
public class StringExample
{
public static void main(String[] args)
{
String str = "FirstName LastName - 1234xx";
String newStr = str.replaceAll("(?<=( - )).*", "$1");
System.out.println(newStr);
}
}
You were on the right track. Just use a lazy dot to consume everything up to and including the dash.
String str = "FirstName LastName - 1234xx";
String newStr = str.replaceAll("^.*-\\s*", "");
System.out.println(newStr);
In Java if you want to split a String by a char or a String you can do that by the split method as follow:
String[] stringWords = myString.split(" ");
But let's say i want now to create a new String using the strings in stringWords using the char * between them. Is there any solutions to do it without for/while instructions?
Here is a clear example:
String myString = "This is how the string should be";
String iWant = "This*is*how*the*string*should*be";
Somebody asks me to be more clear why i don't want just to use replace() function. I don't want to use it simply because the content of the array of strings (array stringWords in my example) changes it's content.
Here is an example:
String myString = "This is a string i wrote"
String[] stringWords = myString.split(" ");
myAlgorithmFucntion(stringWords);
Here is an example of how tha final string changes:
String iWant = "This*is*something*i*wrote*and*i*don't*want*to*do*it*anymore";
If you don't want to use replace or similar, you can use the Apache Commons StringUtils:
String iWant = StringUtils.join(stringWords, "*");
Or if you don't want to use Apache Commons, then as per comment by Rory Hunter you can implement your own as shown here.
yes there is solution to, split String with special characters like '*','.' etc. you have to use special backshlas.
String myString = "This is how the string should be";
iWant = myString.replaceAll(" ","*"); //or iWant = StringUtils.join(Collections.asList(myString.split(" ")),"*");
iWant = "This*is*how*the*string*should*be";
String [] tab = iWant.split("\\*");
Try something like this as you don't want to use replace() function
char[] ans=myString.toCharArray();
for(int i =0; i < ans.length; i++)
{
if(ans[i]==' ')ans[i]='*';
}
String answer=new String(ans);
Try looping the String array:
String[] stringWords = myString.split(" ");
String myString = "";
for (String s : stringWords){
myString = myString + "s" + "*";
}
Just add the logic to deleting the last * of the String.
Using StringBuilder option:
String[] stringWords = myString.split(" ");
StringBuilder myStringBuilder = new StringBuilder("");
for (String s : stringWords){
myStringBuilder.append(s).append("*");
}
Suppose I have a string and I want to check if it contains the following words, then matched words should be removed.
The words are ‘PTE’, ‘LTD’, ‘PRIVATE’ and ‘LIMITED’
I want to check it for both scenerios like if I have word.
String company = "xxx Basit xxx"; //xxx can be ‘PTE’, ‘LTD’, ‘PRIVATE’ and ‘LIMITED’
then output should be just Basit.
and if I have string like:
String company = "xxxBasitxxxMasoodxxx";
then output should be:
BasitMasood
How can I do it?
Thanks
String[] str = {"PTE", "LTD", "PRIVATE", "LIMITED"};
String company = "PTE Basit PTE";
for(int i=0;i<str.length;i++) {
company = company.replaceAll(str[i], "");
}
System.out.println(company.replaceAll("\\s","")); //remove whitespaces
Use String#replaceAll(regex, str)
String company = "PRIVATE Basit PTE";
System.out.println(company.replaceAll("PTE|LTD|PRIVATE|LIMITED", ""));
output:
Basit
String company = //your string
company.replaceAll("PTE|LTD|PRIVATE|LIMITED", "");
"PTEBasitLTDMasoodPRIVATE".replaceAll("PTE|LTD|PRIVATE|LIMITED","");
will result in
BasitMasood
Lets say I have a string whose format is "name_surname". I mean there are 2 dynamic parts, and between them an underscore. I want to separate them and have in a variable the left part (name) and in another the right (surname).
Basically i want the reverse of this: String temp=name+"_"+surname;
Use split();
String[] parts = temp.split("_");
String name = parts[0];
String surname = parts[1]; // <-- comment
Commented line will throw an ArrayIndexOutOfBoundsException if your name does not contain the underscore.
You should use split.
String fullName = "name_surname";
String[] components = fullName.split("_");
String firstName = components[0];
String lastName = components[1];
Just use StringTokenizer
StringTokenizer st = new StringTokenizer(str, "_");
while (st.hasMoreElements()) {
System.out.println(st.nextElement());
}