How to check if a string contains certains letters/characters [duplicate] - java

This question already has answers here:
Test if a string contains any of the strings from an array
(15 answers)
Closed 2 years ago.
If I want to check whether a String contains "CVR", "CPR" and "NR". How do I do so? I tried with following method but got some issues
String testString = "cpr1210";
if (testString.contains("cpr||cvr||nr")) {
System.out.println("yes");
}

I might use String#matches() here, with a regex alternation:
String input = "cpr1210";
if (input.matches("(?i).*(?:cpr|cvr|nr).*")) {
System.out.println("MATCH");
}
If you really wanted to use String#contains(), then you would need to have three separate calls to that method, for each sequence.

As mentioned in my comment to your question, you may use String#contains().
String testString = "cor1210";
// will not print yes, because none of the sequences fit
if (testString.contains("cpr") || testString.contains("cvr") || testString.contains("nr")) {
System.out.println("yes");
}
Make sure your logic-syntax in the if-clause is correct.

You can check whether a String contains another String (a substring) with the String.contains() method. It returns a boolean value. Keep in mind that this method is case sensitive. If you want to do case-insensitive search then use the same technique, convert both input and search string in same case and then call the method.
String testString = "cor1210";
//checks whether testString contains CVR, CPR or NR
if (testString.contains("CVR")||testString.contains("CPR")||testString.contains("NR")){
System.out.println("yes");
}

Related

Java simplyfying a function

I have written a function that checks if a string contains certain words but am not happy with the way the code looks
SO currently i have
private String url = "validator=http://url.com;useraccount=sf4cdamloci;licence=39I8934U401;addedon=343443334;serial=7QW0-5TU8-YN9P-G4FZ;limit=123;days=10"
private String musthave ="validator,useraccount,licence,addedon,serial,limit,days"
So i wanted to check that the url contains the must have words in the string. That eg url must have validator, useraccount, licence.....
SO i have tried the following
Boolean has_validator = false;
Boolean has_licence = false;
.....//others with has_ prefix
String[] split_url = url.split(";")
for(String key_item : split_url){
String[] splitteditem = key_item.split("=");
if (splitteditem[0].equalsIgnoreCase("validator")){
has_validator = true;
}
if (splitteditem[0].equalsIgnoreCase("useraccount")){
has_useraccount = true;
}
....others as well
}
Then later i can easily check
if(has_useraccount && has_...)
The above solution works buts its not scalable as whenever i include a new must have ill have to edit my function.
Is there a better way to achieve this. Am still new to java. I have checked on regex but still i can figure our on how to achieve this.
How do i proceed
Don't use a String to represent a set of Strings. Use... a Set of String: Set<String>. Or at least an array of strings.
Then just use a loop. If any of the word in the set isn't contain in the text, you can immediately return false. If you have never returned false in the loop, then all the words are contained in the text, and you can return true.
Pseudo code:
for each word in the set
if the word is not in the text, return false
end for
return true
If you have a Collection of must-have strings, then you can do something simple like:
mustHave.stream().allMatch(url::contains)
My example isn't doing a case-insensitive check, but you get the idea.

Find the certain word in the string [duplicate]

This question already has answers here:
In Java, how do I check if a string contains a substring (ignoring case)? [duplicate]
(6 answers)
Closed 4 years ago.
I write program, which can recognize the certain word in the string, but i have a question. How to recognize a word in the string without gaps? (in one full string).
String string;
String word;
Scanner scan = new Scanner(System.in);
string = scan.nextLine();
word = scan.nextLine();
if(string.matches(".*\\b" + word +"\\b.*")){
System.out.println("found");
}
else {
System.out.println("Error");
}
If you don't need to actually get the exact string found, just replace your regex part with the following one:
if(string.matches(".*" + word + ".*")){
System.out.println("Found");
}
That should work.
As other validly pointed out, the matches function just tells whether the string matches the regex. If you need to check whether str1 contains str2, you should use contains() function.

How to check if user entered a string that only contains letters? [duplicate]

This question already has answers here:
Check if String contains only letters
(17 answers)
Closed 7 years ago.
How can I check if the user entered a valid string? For example if the user entered "cat" then it would valid, but if the user entered "cat'12ed" then it would be invalid because it should include only letters.
In Java, you can check to see if the String is alpha, or alphanumeric using pattern matching, like so:
public boolean validate(String myString) {
if ( myString == null) return false;
return myString.matches("[A-Za-z0-9]+");
}
There is also commons StringUtils which has an alphanumeric method.
Try regex - this should work for you
System.out.println("cat".matches("[a-zA-Z]+"));
System.out.println("cat'12ed".matches("[a-zA-Z]+"));
If you want your String to be valid if it has only letters you have to use patterns for example:
if(Pattern.matches("[a-zA-Z]+", yourString)) {
//ok it's valid
} else {
//no, it'n not valid
}
You can also use Apache Commons StringUtils: StringUtils.isAlpha().
This question is a possible duplicate of this question.

what happens when converting char to string? (Java) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
I'm using String.valueOf to convert char to string. But the return value seems not exactly same as a string of the same letter. Codes below:
String myString = "s";
char myChar = 's';//both string and char are assigned as letter 's'
String stringFromChar = String.valueOf(myChar);
if (myString == stringFromChar) {
out.println("equal");
} else {
out.println("not equal");
}
Every time it prints not equal. Please help, thanks! :)
== compare the reference, not the actual value. You must use equals to compare the value.
Read this article if you don't understand it's clear and simple.
NEVER DO THIS AGAIN!!! PROMISE ME!!! =P
When comparing strings always, always, always use the equals method. See Below!
String myString = "s";
char myChar = 's';//both string and char are assigned as letter 's'
String stringFromChar = String.valueOf(myChar);
if (myString.equals(stringFromChar)) {
System.out.println("equal");
} else {
System.out.println("not equal");
}
}
what happens when converting char to string?
Well, you are using the String.valueOf(char) method, whose javadoc does not say how it does the conversion. But the behaviour you are seeing strongly suggests that the JVM you are using creates a new String object each time you call the method.
But you should depend on this happening.
The bottom line is that you should always use the equals method to compare strings. Comparing strings with == will often give you false negatives ... depending on how the strings were created / obtained. You've just been bitten by that. Learn.
Reference:
How do I compare strings in Java?

Give comma separated strings as input to sql "IN" clause [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
creating comma seperated string to be given as input to sql “IN” clause
HI,
i have to implement multiple select dropdown,and the selected values shud be formatted to be input to "IN" clause of sql.
Am storing the selected values in a string.But there is no delimiter between values ,so i cannot split the string.Are there any other methods for the string formatting.
Fun solution: Add the values to ArrayList or LinkedList, the call toString(). And replace '['->'(', replace ']'->')'.
If you had a collection of strings and then copied them to 1 string without delimiters you cannot separate them again. Just do not do this. If you still have problems please send more details about your task.
If you know the values of the dropdown and all values are unique and not subsets of each other, then you can use String#contains() or regular expressions to test, which values have been selected.
But it's by far easier to simply add some trivial delimiter (like the common ";") while concatenating the String that holds the selection.
Example for the contains approach
String[] legalValues = {"YES","NO","MAYBE"};
String result = getSelection(); // returns a String like "MAYBEYES"
StringBuilder inClauseBuilder = new StringBuilder();
boolean isFirst = true;
for (String legalValue:legalValues) {
if (!result.contains(legalValue)
continue;
if (isFirst) {
isFirst = false;
} else {
inClauseBuilder.append(",");
}
inClauseBuilder.append("\"").append(legalValue).append("\"");
}
String inClause = inClauseBuilder.toString();
Note - this approach will fail as soon as you have legal values like
String[] legalValues = {"YES","NO","MAYBE-YES", "MAYBE-NO"};
^^^ ^^ ^^^ ^^

Categories

Resources