Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing strings and arrays c#

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.

like image 857
user1852287 Avatar asked Nov 26 '12 04:11

user1852287


People also ask

Can we compare string with array?

The java. util. Arrays class provides two convenient methods for array comparison – equals() and deepEquals() . We can use either method for string array comparison.

Can I use == to compare strings in C?

You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.

Can you compare strings in C?

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.

Can we compare two character arrays in C?

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.


1 Answers

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).

like image 82
Sergey Kalinichenko Avatar answered Sep 30 '22 04:09

Sergey Kalinichenko