This question already has answers here:
Test if a string contains any of the strings from an array
(15 answers)
Closed 8 years ago.
how would you simplify all these conditions?
String s = "The wold is big"
if(s.contains("is") || s.contains("are") || s.contains("was") || s.contains("were"))
{
return s;
}
Since I have to check several cases like those, is there a way to simplify all those conditions?
I would write a utility method for that:
public static boolean containsAny(String s, String... words) {
for (String word : words) {
if (s.contains(word))
return true;
}
return false;
}
And now:
if (containsAny(s, "is", "are", "was", "were")) {...}
Java 8 alternative:
if (Arrays.asList("is", "are", "was", "were").stream().anyMatch(s::contains)) {...}
You can use regex for this using the matches method of the String
sample:
String s = "The wold is big";
if (s.matches("(.*)(is|are|was|were)(.*)")) {
System.out.println("lawl");
}
There is not realy a quicker way to do it. Only if you have a lot of them it would be cleaner to put them in an array and walk over the array.
Also answered here:
Test if a string contains any of the strings from an array
You can pass an array of value to check :
public boolean Contains(String[] list, String elem) {
for (String s: list){
if(elem.contains(s)) {
return true;
}
}
return false;
}
String s = "The wold is big"
String[] conditions = {"is","are","was","were"};
if(Contains(conditions,s))
{
return s;
}
Related
EDIT :
ok, sorry for not so clear question. Let's try other way:
We have an ArayList of names : Peter, John, Adam
We are looking for String name;
If ArrayList contains the String, we want to write the String. If ArrayList doesn't contains the String, we want to add the String into the ArrayList.
If I'm looking for "Adam", then this program is not working, because first it finds name "Peter", then "John", and only after that it finds "Adam". So for the first 2 times, it thinks, "Adam" is not in the list, and acts so.
String findName;
for (i = 0; i < arrayList.size(); i++) {
if (arrayList.get(i).getValue().contains(findName)) {
System.out.println(findName);
break;
}
else
arrayList.add(findString);
}
Original question :
I have a String and an Array (ArrayList). I have to do something, if the String is in the Array and something else, if it is not in the Array. How do I do that?
I can't do it like this :
String myString;
for (i = 0; i < arrayList.size(); i++) {
if (arrayList.get(i).getValue().equals(myString)) {
DO SOMETHING;
break;
}
else
DO SOMETHING ELSE;
}
because it will find the String only once and all the other times it will act, like the arraylist doesn't contains the String.
So I'm doing it like this :
String findString = "0";
String myString;
for (i = 0; i < arrayList.size(); i++) {
if (arrayList.get(i).getValue().equals(myString)) {
DO SOMETHING;
findString = "2"; //when I find the String, I change this
break;
}
if findString == "0"; //if I have not found the String, this happens
DO SOMETHING ELSE;
}
and I have the feeling, it should be not done like this. ;)
I know I can use booleans instead of this way, but it's the same in other way. Isn't there total different way of doing this correctly?
Cleanest way is as follows: Declare a method which returns whether the string is in the array:
public boolean arrContainsStr(String str, String[] arr) {
for (int i = 0; i < arr.length; i++) {
if (arr[i].equals(str)) {
return true;
}
}
return false;
}
Then use this method in your code like this:
String myString;
String[] myArray;
if (arrContainsStr(myString, myArray)) {
DO SOMETHING;
}else {
DO SOMETHING ELSE;
}
This is for primitive string arrays. Note that if you are using an ArrayList or similar, you can simply use the .contains(myString) method to check if the list contains your string. Documentation here: https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#contains(java.lang.Object)
This question is a bit odd, but just reading your first sentence, if you want to see if a List e.g. ArrayList contains an object (e.g. a String) you can just use the contains(Object o) method rather than looping through. I must be missing your point. In any case, an example:
String stringToFind = "Foo";
List<String> stringList = new ArrayList<>();
stringList.add("Foo");
if (stringList.contains(stringToFind)) {
System.out.println("String found");
} else {
System.out.println("String not found");
}
Output: String found. (In this example).
Couldn't you use .contains as below to check if the String is in the list?
if(arrayList.contains(myString)){
// DO SOMETHING
} else {
// DO SOMETHING ELSE
}
You could set a boolean to true if you find your value then break.
If you don't find the value, the boolean will stay to false.
Then you do the if
Its a little vague so I'm not sure if this is what you want, but if you remove the break in the first segment of code i think you will get what you want. do you want it do DO SOMETHING for every occurrence of the string or just the first one. also if you do need the break you could check the value of i after the loop terminates so
if(i==arrayList.size())
{
//String found
}
else
{
//String not found
}
This question already has answers here:
What is the difference between == and equals() in Java?
(26 answers)
Closed 7 years ago.
import java.util.Scanner;
class Pal {
public static boolean Palindrome(StringBuffer str) {
StringBuffer str1 = str.reverse();
System.out.println(str1);
if (str == str1) {
return true;
} else {
return false;
}
}
public static void main(String args[]) {
System.out.println("Enter a string");
StringBuffer str = new StringBuffer();
Scanner input = new Scanner(System.in);
str.append(input.nextLine());
boolean result = Palindrome(str);
System.out.println(result);
}
}
How sholud I improve my code such that values come out to be perfectly correct?
if (str == str1)
{
return true;
}
else
{
return false;
}
is the same as
return str == str1;
However, this still "won't work" correctly because
Code should equals() for comparing objects (including Strings and StringBuffers) and
StringBuffer does not have a useful equals.
A correction, taking both of these into account, would be:
return str.toString().equals(str2.toString());
In this case we first get the current String content of both StringBuffer objects and then compare it with String.equals(String), which works as expected.
An alternative would be to bypass the StringBuffers in this case and directly use Strings; this would allow skipping the toString calls.
This question already has answers here:
How do I determine whether an array contains a particular value in Java?
(30 answers)
Closed 7 years ago.
I want to compare from a void main method where there is a array and a string. so what I want to do is to compare with if name is in the array. return true else return false. But I cant get it to work. It gives me false on both. And I don't know why?
public boolean isActor(String name) {
if(name.equals(actors)) {
return true;
}else {
return false;
}
}
public static void main(String[] args) {
String[] actors = {"Ulla Skoog", "Suzanne Reuter", "Peter Dalle"} ;
Dvd d1 = new Dvd(10327, "Yrrol", "Peter Dalle", actors, 88);
System.out.println("Medverkar Kalle Kula i Lorry: " + d1.isActor("Kalle kula"));
System.out.println("Medverkar Ulla Skoog i Lorry: " + d1.isActor("Ulla Skoog"));
}
Any help would be appreciated !
EDIT: So I tried to do if(Arrays.asList(actors).contains(name)) and yes it worked. Problem is I might now be allowed to do it under a test which can make me losing points and I tried to make a for loop and by that make a equals statement but still getting the same result which is both false.
EDIT2: Also tried to do this
public boolean isActor(String name) {
for(String s: actors){
if(s.equals(actors))
return true;
}
return false;
}
but still got the same result of both false
EDIT3:
What I want to do is to make e method which is ( public boolean isActor(String name) { ) and with that I want to make a if-statement which should make a algorithm by saying "If this name is on this array. make it say true. If its not in the array. Say its false." Thats what im trying to do.
You have to test each item in array:
public boolean isActor(String name) {
for (String actor : actors) {
if (name.equals(actor) {
return true;
}
}
return false;
}
public boolean isActor(String name, List<String> actorList) {
if(actorList.contains(name)) {
return true;
}else {
return false;
}
}
public static void main(String[] args) {
String[] actors = {"Ulla Skoog", "Suzanne Reuter", "Peter Dalle"} ;
List<String> actorList = Arrays.asList ( actors);
Dvd d1 = new Dvd(10327, "Yrrol", "Peter Dalle", actors, 88);
System.out.println("Medverkar Kalle Kula i Lorry: " + d1.isActor("Kalle kula",actors));
System.out.println("Medverkar Ulla Skoog i Lorry: " + d1.isActor("Ulla Skoog",actors));
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
Why is this coming out as false?
public class practice
{
public static void main(String [] args)
{
System.out.println(startHi("hi "));
}
public static boolean startHi(String str)
{
System.out.println(str.substring(0,2));
if(str.length() < 2)
{
return false;
}
else if(str.substring(0,2) ==("hi"))
{
return true;
}
else
{
return false;
}
}
}
You should use the .equals method to check for equality of strings, not ==. See here.
Using == is checking to see if the objects have the same address in memory. That's not usually what you're looking for when checking if the value of two strings are the same.
I have an array of strings (keywords), and I need to check how many of those strings existing within a larger string (text read from file). I need the check to be case insensitive.
At this moment what I do is this:
private void findKeywords() {
String body = email.getMessage();
for (String word : keywords) {
if (body.toLowerCase().contains(word.toLowerCase())) {
//some actions }
if (email.getSubject().contains(word)) {
//some actions
}
}
}
From reading questions in here another solution came up:
private void findKeywords() {
String body = email.getMessage();
for (String word : keywords) {
boolean body_match = Pattern.compile(Pattern.quote(word), Pattern.CASE_INSENSITIVE).matcher(body).find();
boolean subject_match = Pattern.compile(Pattern.quote(word), Pattern.CASE_INSENSITIVE).matcher(email.getSubject()).find();
if (body_match) {
rating++;
}
if (subject_match) {
rating++;
}
}
}
Which of these solutions is more efficient? Also is there another way to do this that is better? Any accepted solutions must be simple to implement(on par with the above) and preferably without external libraries as this is not very important issue in this case.
Both of the solutions seem viable to me. One improvement I would suggest is moving functions out of the loop. In your current code you are repeatedly doing actions such as toLowerCase() and Pattern.compile which you only need to do once.
Obviously there are much faster methods to solve this problem, but they require much more complex code than these 5-liners.
Better: build a single pattern with all keywords. Then search on that pattern. Assuming your keywords do not contain meta-characters (characters with special meanings in patterns), then use:
StringBuilder keywordRegex = new StringBuilder();
for (String w : keywords) {
keywordRegex.append("|"+w);
}
Pattern p = Pattern.compile(keywordRegex.substring(1));
Matcher m = new p.matcher(textToMatch);
while (m.find()) {
// match is at m.start(); word is m.group(0);
}
Much more efficient than iterating through all keywords: pattern compilation (once) will have generated an automata that looks for all keywords at once.
I think the explicit regex solution you mentioned would be more efficient since it doesn't have the toLowerCase operation, which would copy the input string in memory and make chars lowercase.
Both solutions should be practical and your question is mostly academic, but I think the regexes provide cleaner code.
If your email bodies are very large, writing a specialized case-insensitive contains may be justified, because you can avoid calling toUpperCase() on big strings:
static bool containsIgnoreCase(String big, String small) {
if (small == null || big == null || small.length() > big.length()) {
return false;
}
String smallLC = small.toLowerCase();
String smallUC = small.toUpperCase();
for (int i = 0; i < big.length(); ++i) {
if (matchesAt(big, i, smallLC, smallUC)) {
return true;
}
}
return false;
}
private static bool matchesAt(String big, int index, String lc, String uc) {
if (index + lc.length() > big.length()) {
return false;
}
for (int i = 0; i < lc.length(); ++i) {
char c = big.charAt(i + index);
if ((c != lc.charAt(i)) && (c != uc.charAt(i))) {
return false;
}
}
return true;
}