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
Related
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.
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("*");
}
What is the easiest way to get every word in a string other than the last word in a string?
Up until now I have been using the following code to get the last word:
String listOfWords = "This is a sentence";
String[] b = listOfWords.split("\\s+");
String lastWord = b[b.length - 1];
And then getting the rest of the the string by using the remove method to remove the last word from the string.
I don't want to have to use the remove method. Is there a way similar to the above set of code to get the string of words without the last word and last space?
Like this:
String test = "This is a test";
String firstWords = test.substring(0, test.lastIndexOf(" "));
String lastWord = test.substring(test.lastIndexOf(" ") + 1);
You could get the lastIndexOf the white space and use a substring like below:
String listOfWords = "This is a sentence";
int index = listOfWords.lastIndexOf(" ");
System.out.println(listOfWords.substring(0, index));
System.out.println(listOfWords.substring(index+1));
Output:
This is a
sentence
Try using the method String.lastIndexOf in combination with String.substring.
String listOfWords = "This is a sentence";
String allButLast = listOfWords.substring(0, listOfWords.lastIndexOf(" "));
I added one line to your code. Nothing was removed here.
String listOfWords = "This is a sentence";
String[] b = listOfWords.split("\\s+");
String lastWord = b[b.length - 1];
String rest = listOfWords.substring(0, listOfWords.indexOf(lastWord)).trim(); // Added
System.out.println(rest);
This will suit your needs:
.split("\\s+[^\\s]+$|\\s+")
For example:
"This is a sentence".split("\\s+[^\\s]+$|\\s+");
Returns:
[This, is, a]
public class StringArray {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String sentence = "this is a sentence";
int index = sentence.lastIndexOf(" ");
System.out.println(sentence.substring(0, index));
}
}
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());
}
I am getting this string from a program
[user1, user2]
I need it to be splitted as
String1 = user1
String2 = user2
You could do this to safely remove any brackets or spaces before splitting on commas:
String input = "[user1, user2]";
String[] strings = input.replaceAll("\\[|\\]| ", "").split(",");
// strings[0] will have "user1"
// strings[1] will have "user2"
Try,
String source = "[user1, user2]";
String data = source.substring( 1, source.length()-1 );
String[] split = data.split( "," );
for( String string : split ) {
System.out.println(string.trim());
}
This will do your job and you will receive an array of string.
String str = "[user1, user2]";
str = str.substring(1, str.length()-1);
System.out.println(str);
String[] str1 = str.split(",");
Try the String.split() methods.
From where you are getting this string.can you check the return type of the method.
i think the return type will be some array time and you are savings that return value in string . so it is appending [ ]. if it is not the case you case use any of the methods the users suggested in other answers.
From the input you are saying I think you are already getting an array, don't you?
String[] users = new String[]{"user1", "user2"};
System.out.println("str="+Arrays.toString(str));//this returns your output
Thus having this array you can get them using their index.
String user1 = users[0];
String user2 = users[1];
If you in fact are working with a String then proceed as, for example, #WhiteFang34 suggests (+1).