How would i go about making a function that would return true
if a string contains any element of an array?
Something like this:
string str = "hi how are you";
string[] words = {"hi", "hey", "hello"};
would return true
.
The java. util. Arrays class provides two convenient methods for array comparison – equals() and deepEquals() . We can use either method for string array comparison.
You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.
We compare the strings by using the strcmp() function, i.e., strcmp(str1,str2). This function will compare both the strings str1 and str2. If the function returns 0 value means that both the strings are same, otherwise the strings are not equal.
From the documentation on strcmp: Compares the C string str1 to the C string str2. This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.
You can do it like this:
var array = new[] {"quick", "brown", "fox"};
var myString = "I love foxes.";
if (array.Any(s => myStr.IndexOf(s) >= 0)) {
// One of the elements is there
}
This approach does not require that the element be a full word (i.e. the above fragment would return true
, even though the word "fox"
is not present there as a single word).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With