Find word in array c

I need to search a string in the string array. I dont want to use any for looping in it

string [] arr = {"One","Two","Three"};

string theString = "One"

I need to check whether theString variable is present in arr.

Neo's user avatar

Neo

3,2897 gold badges35 silver badges44 bronze badges

asked Nov 5, 2008 at 12:12

balaweblog's user avatar

0

Well, something is going to have to look, and looping is more efficient than recursion (since tail-end recursion isn’t fully implemented)… so if you just don’t want to loop yourself, then either of:

bool has = arr.Contains(var); // .NET 3.5

or

bool has = Array.IndexOf(arr, var) >= 0;

For info: avoid names like var — this is a keyword in C# 3.0.

jcolebrand's user avatar

jcolebrand

16.3k11 gold badges75 silver badges121 bronze badges

answered Nov 5, 2008 at 12:16

Marc Gravell's user avatar

Marc GravellMarc Gravell

1.0m260 gold badges2545 silver badges2884 bronze badges

Every method, mentioned earlier does looping either internally or externally, so it is not really important how to implement it. Here another example of finding all references of target string

       string [] arr = {"One","Two","Three"};
       var target = "One";
       var results = Array.FindAll(arr, s => s.Equals(target));

answered Nov 5, 2008 at 13:56

Tamir's user avatar

TamirTamir

2,50516 silver badges23 bronze badges

2

Does it have to be a string[] ? A List<String> would give you what you need.

List<String> testing = new List<String>();
testing.Add("One");
testing.Add("Two");
testing.Add("Three");
testing.Add("Mouse");
bool inList = testing.Contains("Mouse");

answered Nov 5, 2008 at 12:18

ZombieSheep's user avatar

ZombieSheepZombieSheep

29.5k12 gold badges66 silver badges114 bronze badges

bool exists = arr.Contains("One");

answered Nov 5, 2008 at 12:19

mohammedn's user avatar

mohammednmohammedn

2,9263 gold badges23 silver badges30 bronze badges

0

I think it is better to use Array.Exists than Array.FindAll.

answered Mar 26, 2010 at 11:53

Joe Cheri Ross's user avatar

0

Its pretty simple. I always use this code to search string from a string array

string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
int pos = Array.IndexOf(stringArray, value);
if (pos > -1)
{
    return true;
}
else
{
    return false;
}

answered Nov 6, 2013 at 10:15

Sharp Coders's user avatar

If the array is sorted, you can use BinarySearch. This is a O(log n) operation, so it is faster as looping. If you need to apply multiple searches and speed is a concern, you could sort it (or a copy) before using it.

answered Nov 5, 2008 at 12:19

GvS's user avatar

GvSGvS

51.9k16 gold badges101 silver badges139 bronze badges

Each class implementing IList has a method Contains(Object value). And so does System.Array.

answered Nov 5, 2008 at 12:18

VolkerK's user avatar

VolkerKVolkerK

95.1k20 gold badges162 silver badges226 bronze badges

1

Why the prohibition «I don’t want to use any looping»? That’s the most obvious solution. When given the chance to be obvious, take it!

Note that calls like arr.Contains(...) are still going to loop, it just won’t be you who has written the loop.

Have you considered an alternate representation that’s more amenable to searching?

  • A good Set implementation would perform well. (HashSet, TreeSet or the local equivalent).
  • If you can be sure that arr is sorted, you could use binary search (which would need to recurse or loop, but not as often as a straight linear search).

answered Nov 5, 2008 at 12:57

bendin's user avatar

bendinbendin

9,3941 gold badge39 silver badges37 bronze badges

You can use Find method of Array type. From .NET 3.5 and higher.

public static T Find<T>(
    T[] array,
    Predicate<T> match
)

Here is some examples:

// we search an array of strings for a name containing the letter “a”:
static void Main()
{
  string[] names = { "Rodney", "Jack", "Jill" };
  string match = Array.Find (names, ContainsA);
  Console.WriteLine (match);     // Jack
}
static bool ContainsA (string name) { return name.Contains ("a"); }

Here’s the same code shortened with an anonymous method:

string[] names = { "Rodney", "Jack", "Jill" };
string match = Array.Find (names, delegate (string name)
  { return name.Contains ("a"); } ); // Jack

A lambda expression shortens it further:

string[] names = { "Rodney", "Jack", "Jill" };
string match = Array.Find (names, n => n.Contains ("a"));     // Jack

answered Nov 7, 2014 at 14:09

Yuliia Ashomok's user avatar

Yuliia AshomokYuliia Ashomok

8,1371 gold badge58 silver badges68 bronze badges

At first shot, I could come up with something like this (but it’s pseudo code and assuming you cannot use any .NET built-in libaries). Might require a bit of tweaking and re-thinking, but should be good enough for a head-start, maybe?

int findString(String var, String[] stringArray, int currentIndex, int stringMaxIndex)
    {
    if currentIndex > stringMaxIndex 
       return (-stringMaxIndex-1);
    else if var==arr[currentIndex] //or use any string comparison op or function
       return 0;
    else 
       return findString(var, stringArray, currentIndex++, stringMaxIndex) + 1 ;
    }



    //calling code
    int index = findString(var, arr, 0, getMaxIndex(arr));

    if index == -1 printOnScreen("Not found");
    else printOnScreen("Found on index: " + index);

answered Nov 5, 2008 at 12:31

Salman Kasbati's user avatar

In C#, if you can use an ArrayList, you can use the Contains method, which returns a boolean:

if MyArrayList.Contains("One")

answered Nov 5, 2008 at 12:49

DOK's user avatar

DOKDOK

32.2k7 gold badges60 silver badges92 bronze badges

1

You can check the element existence by

arr.Any(x => x == "One")

answered Dec 5, 2014 at 8:55

Ahmad's user avatar

AhmadAhmad

8,42310 gold badges73 silver badges128 bronze badges

it is old one ,but this is the way i do it ,

enter code herevar result = Array.Find(names, element => element == «One»);

answered Jul 13, 2020 at 14:37

Ali's user avatar

AliAli

1,05216 silver badges21 bronze badges

I’m surprised that no one suggested using Array.IndexOf Method.

Indeed, Array.IndexOf has two advantages :

  • It allows searching if an element is included into an array,
  • It gets at the same time the index into the array.
int stringIndex = Array.IndexOf(arr, theString);
if (stringIndex >= 0)
{
    // theString has been found
}

Inline version :

if (Array.IndexOf(arr, theString) >= 0)
{
    // theString has been found
}

answered Jul 26, 2020 at 19:48

Using Contains()

string [] SomeArray = {"One","Two","Three"};
bool IsExist = SomeArray.Contains("One");
Console.WriteLine("Is string exist: "+ IsExist);

Using Find()

string [] SomeArray = {"One","Two","Three"};
var result = Array.Find(SomeArray, element => element == "One");
Console.WriteLine("Required string is: "+ result);

Another simple & traditional way, very useful for beginners to build logic.

string [] SomeArray = {"One","Two","Three"};
foreach (string value in SomeArray) {
    if (value == "One") { 
        Console.WriteLine("Required string is: "+ value);
    }
 }

answered Dec 24, 2022 at 19:45

Billu's user avatar

BilluBillu

2,66525 silver badges47 bronze badges

Ezoic

Write a C program to search a string in the list of strings. Take input from the user. In this program, we will use two-dimensional strings. Two-dimensional strings mean the array of strings. It is similar to the two-dimensional array but it is a collection of strings. Prerequisites:- 2d array of strings in C

#include<stdio.h>
#include<string.h>
int main()
{
   char str[20][50], s1[50];
   int n, i, found=0;

   printf("Enter how many string (names): ");
   scanf("%d", &n);

   printf("Enter %d strings:n", n);
   for(i=0; i<n; i++)
   {
     scanf("%s", str[i]);
   }

   printf("Enter a string to search: ");
   scanf("%s", s1);

   for(i=0; i<n; i++)
   {
     if(strcmp(s1, str[i]) == 0)
     {
       found=1;
       printf("Found in row-%dn", i+1);
     }
   }

   if(found==0) printf("Not found");
   return 0;
}

Output for the different test-cases:-

Enter how many string (names): 5
Enter 5 strings:
Java
HTML
Python
C++
Programming
Enter a string to search: Python
Found in row-3

Enter how many string (names): 3
Enter 3 strings:
C
C++
.NET
Enter string to search: Java
Not found

C program to search a string in the list of strings, In this program first, we take input from user. To read the string we can use gets(), fgets(), [^n] and other methods. But you may get different behavior of the program.

Later each string is compared with s1 (s1 is the string to search). If string is found then strcmp() returns zero, otherwise non-zero. Finally, we got the result.

If we ignore the case sensitivity then “Python”, “python” and “PYTHON” all are the same, and If you want to ignore this case sensitivity also in the program then you can use stricmp() or strcasecmp().

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Similar C programming examples on Arrays

  • Sum of Array elements
  • Display even & odd numbers in an array
  • Sum and count of even and odd numbers in an array
  • Count positive negative and zeros in the array
  • Sum of positive and negative numbers
  • Average and numbers greater than average in the array
  • Find Smallest and largest Array element
  • First maximum & minimum, Second maximum & minimum
  • Sort a list of an array element
  • Search an Array element
  • Search position of nth times occurred element in an array
  • C program to insert an element in an array
  • C program to delete an element in an array
  • Passing a multidimensional array to Function
  • Find Largest and smallest in a 2D array with their position
  • Store temperature of two Cities for a week & display
  • Matrix Operations – Addition, Multiplication, Transpose

Ezoic

This post will discuss how to check the existence of a given element in an array in C#. The solution should return true if the array contains the specified value; otherwise, false.

1. Using Enumerable.Contains() method (System.Linq)

The Enumerable.Contains() method provides a simple, clean way to determine whether a sequence contains a specified element or not. The following example demonstrates the usage of the Contains() method:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

using System;

using System.Linq;

public static class Extensions

{

    public static bool find<T>(this T[] array, T target) {

        return array.Contains(target);

    }

}

public class Example

{

    public static void Main()

    {

        int[] array = { 1, 2, 3, 4, 5 };

        int target = 4;

        bool isExist = array.find(target);

        if (isExist) {

            Console.WriteLine(«Element found in the array»);

        }

        else {

            Console.WriteLine(«Element not found in the given array»);

        }

    }

}

/*

    Output: Element found in the array

*/

Download  Run Code

2. Using Array.Exists() method

The Array.Exists() method is the recommended solution is to check the existence of an element in an array. The following code example shows how to implement this.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

using System;

public static class Extensions

{

    public static bool find<T>(this T[] array, T target) {

        return Array.Exists(array, x => x.Equals(target));

    }

}

public class Example

{

    public static void Main()

    {

        int[] array = { 1, 2, 3, 4, 5 };

        int target = 4;

        bool isExist = array.find(target);

        if (isExist) {

            Console.WriteLine(«Element found in the array»);

        }

        else {

            Console.WriteLine(«Element not found in the given array»);

        }

    }

}

/*

    Output: Element found in the array

*/

Download  Run Code

3. Using Array.IndexOf() method

Another good solution is to use the Array.IndexOf() method that returns the index of the first occurrence of the specified element in this array and -1 if there is no such element.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

using System;

public static class Extensions

{

    public static bool find<T>(this T[] array, T target) {

        return Array.IndexOf(array, target) != 1;

    }

}

public class Example

{

    public static void Main()

    {

        int[] array = { 1, 2, 3, 4, 5 };

        int target = 4;

        bool isExist = array.find(target);

        if (isExist) {

            Console.WriteLine(«Element found in the array»);

        }

        else {

            Console.WriteLine(«Element not found in the given array»);

        }

    }

}

/*

    Output: Element found in the array

*/

Download  Run Code

4. Using Array.FindIndex() method

Array.FindIndex() returns the index of the first element that satisfies the provided predicate. If no element satisfies the condition, FindIndex returns -1.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

using System;

public static class Extensions

{

    public static bool find<T>(this T[] array, T target) {

        return Array.FindIndex(array, x => x.Equals(target)) != 1;

    }

}

public class Example

{

    public static void Main()

    {

        int[] array = { 1, 2, 3, 4, 5 };

        int target = 4;

        bool isExist = array.find(target);

        if (isExist) {

            Console.WriteLine(«Element found in the array»);

        }

        else {

            Console.WriteLine(«Element not found in the given array»);

        }

    }

}

/*

    Output: Element found in the array

*/

Download  Run Code

5. Using HashSet

HashSet class provides the Contains method to determine whether the set object contains the specified element. The following example converts the given array to a set and calls its Contains method:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

using System;

using System.Collections.Generic;

public static class Extensions

{

    public static bool find<T>(this T[] array, T target) {

        return new HashSet<T>(array).Contains(target);

    }

}

public class Example

{

    public static void Main()

    {

        int[] array = { 1, 2, 3, 4, 5 };

        int target = 4;

        bool isExist = array.find(target);

        if (isExist) {

            Console.WriteLine(«Element found in the array»);

        }

        else {

            Console.WriteLine(«Element not found in the given array»);

        }

    }

}

/*

    Output: Element found in the array

*/

Download  Run Code

6. Using Enumerable.Where() method (System.Linq)

The System.Linq.Enumerable.Where() method filters a sequence of values based on a predicate. The following code example demonstrates how we can use Where() to find the first occurrence of the specified element in this array.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

using System;

using System.Linq;

public static class Extensions

{

    public static bool find<T>(this T[] array, T target)

    {

        try {

            array.Where(i => i.Equals(target)).First();

            // or

            // array.First(i => i.Equals(target));

            return true;

        }

        catch (InvalidOperationException) {

            return false;

        }

    }

}

public class Example

{

    public static void Main()

    {

        int[] array = { 1, 2, 3, 4, 5 };

        int target = 4;

        bool isExist = array.find(target);

        if (isExist) {

            Console.WriteLine(«Element found in the array»);

        }

        else {

            Console.WriteLine(«Element not found in the given array»);

        }

    }

}

/*

    Output: Element found in the array

*/

Download  Run Code

 
We can avoid the try-catch block by setting the default value with the DefaultIfEmpty() method:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

using System;

using System.Linq;

public static class Extensions

{

    public static bool find(this int[] array, int target)

    {

        return (array.Where(i => i.Equals(target))

                    .DefaultIfEmpty(1)

                    .First()) != 1;

    }

}

public class Example

{

    public static void Main()

    {

        int[] array = { 1, 2, 3, 4, 5 };

        int target = 4;

        bool isExist = array.find(target);

        if (isExist) {

            Console.WriteLine(«Element found in the array»);

        }

        else {

            Console.WriteLine(«Element not found in the given array»);

        }

    }

}

/*

    Output: Element found in the array

*/

Download  Run Code

7. Using Array.FindAll() method

Array.FindAll() method returns an array containing all the elements that match the specified predicate. We can use it as following to check for the existence of an element in the array.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

using System;

public static class Extensions

{

    public static bool find<T>(this T[] array, T target)

    {

        T[] results = Array.FindAll(array, x => x.Equals(target));

        return results.Length > 0;

    }

}

public class Example

{

    public static void Main()

    {

        int[] array = { 1, 2, 3, 4, 5 };

        int target = 4;

        bool isExist = array.find(target);

        if (isExist) {

            Console.WriteLine(«Element found in the array»);

        }

        else {

            Console.WriteLine(«Element not found in the given array»);

        }

    }

}

/*

    Output: Element found in the array

*/

Download  Run Code

8. Performing Linear Search

A naive solution is to perform a linear search on the given array to determine whether the target element is present in the array.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

using System;

using System.Collections.Generic;

public static class Extensions

{

    public static bool find<T>(this T[] array, T target)

    {

        EqualityComparer<T> comparer = EqualityComparer<T>.Default;

        for (int i = 0; i < array.Length; i++)

        {

            if (comparer.Equals(array[i], target)) {

                return true;

            }

        }

        return false;

    }

}

public class Example

{

    public static void Main()

    {

        int[] array = { 1, 2, 3, 4, 5 };

        int target = 4;

        bool isExist = array.find(target);

        if (isExist) {

            Console.WriteLine(«Element found in the array»);

        }

        else {

            Console.WriteLine(«Element not found in the given array»);

        }

    }

}

/*

    Output: Element found in the array

*/

Download  Run Code

That’s all about finding an element in an array in C#.

C program to search all occurrences of a word in a given string – In this article, we will particularise the different ways to search all occurrences of a word in a given string in C programming.

Suitable examples and sample programs have also been added so that you can understand the whole thing very clearly. The compiler has also been added with which you can execute it yourself.

The ways used in this specific piece are as follows:

  • Using Standard Method
  • Using Function
  • C Program To Count Frequency Of Each Character In String | C Programs
  • C Program To Remove First Occurrence Of A Character From String
  • C Program Hollow Diamond Star Pattern | C Programs

A string is nothing but an array of characters. The value of a string is determined by the terminating character. Its value is considered to be 0.

C Program To Search All Occurrences Of A Word In String

The image uploaded above states that first, you need to enter the string concerned.

The string entered here is as follows:

“hello world hello world hello world”

In the next step, you need to specify what is the word that you want to be searched.

The word “world” is listed for the search part.

Thus, it is seen that the word “world” is spotted at locations 6, 18 and 30.

Thus, the numerous means to do so in C programming are as follows:

Using Standard Method

  1. The function gets(s) reads the entered string and it stores the string in the character arrays[].

2) The gets(w) function reads the entered word and saves in the character array w[].

3) For loop iterates through the string and finds the index values of the white spaces, stores the index values in the integer array a[].

4) The for loop iterates through the white spaces of the string with the structure for(i=0; i<k;i++)

a) Initialize n=a[i]-j i.e first white space index-j

b) If the length of the word is equal to n

b.1) Then t=0, compare the first element of the word with the first element of the string as s[l+j]==w[l]. If matched then increase the ‘t’ value. Repeat this for all elements of the word by increasing l value. If t=length of the word then increase the ‘found’ value by 1 and print the location of the occurrence of the word in the string i.e. j.

If the given word has not occurred before the first whitespace then initialize j=a[i]+1 and go to the next index of the whitespace by increasing i value. Repeat until i<k.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

#include <stdio.h>

#include <string.h>

int main()

{

    char s[1000],w[1000];  

    int n,a[1000],i,j,k=0,l,found=0,t=0;

    printf(«Enter  the string : «);

    gets(s);

    printf(«Enter word to be searched: «);

    gets(w);

    for(i=0;s[i];i++)

    {

     if(s[i]==‘ ‘)

     {

     a[k++]=i;

}

}

a[k++]=i;

j=0;

for(i=0;i<k;i++)

{

n=a[i]j;

if(n==strlen(w))

{

t=0;

for(l=0;w[l];l++)

{

if(s[l+j]==w[l])

{

t++;

}

}

if(t==strlen(w))

    {

found++;

printf(«word ‘%s’  is occurred at location=%d n»,w,j);

    }

}

j=a[i]+1;

}

}

Output:

Enter  the string: hello world hello world hello world

Enter word to be searched: world

word ‘world’  is occurred at location=6

word ‘world’  is occurred at location=18

word ‘world’  is occurred at location=30

Using Function

  1. The main() call the check(char *s, char *w) function to find all occurrences of the word in the given string.

2) The function

a) Iterates through the string using for loop(i=0;s[i];i++) and finds the index values of the white spaces and place the index values in the integer array a[].

b) j=0, Iterate through the white spaces until i<k,

Initialize n=a[i]-j

b.1) If the length of the word is equal to the first index value of white space then compare each letter of the word with the elements of the string as s[i+l]==w[l] by increasing l value. If matched then t++. If ‘t’ is equal to the length of the word then print the location of occurrence of the word.

If the word has not occurred before the first whitespace then initialize j=a[i]+1 and go for next index of the white space. Repeat the loop until i<k.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

#include <stdio.h>

#include <string.h>

void check(char *s,char *w)

{

    int n,a[1000],i,j,k=0,l,found=0,t=0;

    for(i=0;s[i];i++)

    {

     if(s[i]==‘ ‘)

     {

     a[k++]=i;

}

}

a[k++]=i;

j=0;

for(i=0;i<k;i++)

{

n=a[i]j;

if(n==strlen(w))

{

t=0;

for(l=0;w[l];l++)

{

if(s[l+j]==w[l])

{

t++;

}

}

if(t==strlen(w))

    {

found++;

printf(«word ‘%s’  is occurred at location=%d n»,w,j);

    }

}

j=a[i]+1;

}

}

int main()

{

    char s[1000],w[1000];

int n;

    printf(«Enter  the string : «);

    gets(s);

    printf(«Enter word to be searched: «);

    gets(w);

     check(s,w);

}

Output:

Enter  the string: hello world welcome to cbeginners welcome to programming

Enter word to be searched: to

The word ‘to’  is occurred at location=20

The word ‘to’  is occurred at location=42

Write a C program to find a string in an array of strings. The program should take input from the user.

Example,

Input
Number of Strings: 5
Ravil
James
Jeffree
Shane
PewDiePie

String to Search: PewDiePie

Output
PewDiePie is present at the 4th row

We will use a 2D character array to store the strings. Each row of the 2D will store one string. The program is very simple. We loop through each row of the 2D array and compare each string of the array with the string that we want to search. We will use strcmp() to compare the two strings.

Syntax for strcmp()

int strcmp(const char *str1, const char *str2);

strcmp() compares string str1 to string str2. The function returns 0 if both the strings are same.

#include <stdio.h>
#include <string.h>

int main() {

	char str[100];	// string to search
	char s[100][100];	// array of string
	int n;	// number of string in the array
	int i;

	printf("Enter Number of Strings: ");
	scanf("%d", &n);

	for (i = 0; i < n; ++i) {
		scanf("%s", s[i]);
	}

	printf("Enter string to search: ");
	scanf("%s", str);

	for (i = 0; i < n; ++i) {
		if (!strcmp(str, s[i])) {
			break;
		}
	}

	if (i != n) {
		printf("%s is present in the array at row %d", str, i);
	}
	else {
		printf("%s is not present in the array", str);
	}

}

Output

Enter Number of Strings: 5
James
Shane
Ravil
Smith
Nadi
Enter string to search: Ravil
Ravil is present in the array at row 2

Read

  • C Program to Search a Word in a Sentence
  • C Program to find a word in a given file and print locations of all it’s occurrences
  • Program to remove alternate digits from an integer
  • Find the square root of a number without using sqrt()

Often you need to search element(s) in an array based on some logic in C#. Use the Array.Find() or Array.FindAll() or Array.FindLast() methods to search for an elements that match with the specified condition.

Array.Find()

The Array.Find() method searches for an element that matches the specified conditions using predicate delegate, and returns the first occurrence within the entire Array.

public static T Find<T>(T[] array, Predicate<T> match);

As per the syntax, the first parameter is a one-dimensional array to search and the second parameter is the predicate deligate which can be a lambda expression.
It returns the first element that satisfy the conditions defined by the predicate expression; otherwise, returns the default value for type T.

The following example finds the first element that matches with string «Bill».

string[] names = { "Steve", "Bill", "Bill Gates", "Ravi", "Mohan", "Salman", "Boski" };
var stringToFind = "Bill";
 
var result = Array.Find(names, element => element == stringToFind); // returns "Bill"

The following example returns the first element that starts with «B».

string[] names = { "Steve", "Bill", "Bill Gates", "James", "Mohan", "Salman", "Boski" };
 
var result = Array.Find(names, element => element.StartsWith("B")); // returns Bill

The following example returns the first element, whose length is five or more.

string[] names = { "Steve", "Bill", "James", "Mohan", "Salman", "Boski" };

var result = Array.Find(names, element => element.Length >= 5); // returns Steve

Notice that the Array.Find() method only returns the first occurrence and not all matching elements. Use the Array.FindAll() method to retrieve all matching elements.

Array.FindAll()

The Array.FindAll() method returns all elements that match the specified condition.

public static T[] FindAll<T>(T[] array, Predicate<T> match)

As per the syntax, the first parameter is a one-dimensional array to search and the second parameter is the predicate deligate which can be a lambda expression.
It returns all the elements that satisfy the condition defined by the predicate expression.

The following example finds all elements that match with «Bill» or «bill».

string[] names = { "Steve", "Bill", "bill", "James", "Mohan", "Salman", "Boski" };
var stringToFind = "bill";
           
string[] result = Array.FindAll(names, element => element.ToLower() == stringToFind); // return Bill, bill

The following example finds all elements that start with B.

string[] names = { "Steve", "Bill", "James", "Mohan", "Salman", "Boski" };

string[]  result = Array.FindAll(names, element => element.StartsWith("B")); // return Bill, Boski

The following example finds all elements whose length is five or more.

string[] names = { "Steve", "Bill", "James", "Mohan", "Salman", "Boski" };
 
string[] result = Array.FindAll(names, element => element.Length >= 5); // returns Steve, James, Mohan, Salman, Boski 

Array.FindLast()

The Array.Find() method returns the first element that matches the condition. The Array.FindLast() method returns the last element that matches the specified condition in an array.

public static T FindLast<T>(T[] array, Predicate<T> match)

As per the syntax, the first parameter is a one-dimensional array to search and the second parameter is the predicate deligate which can be a lambda expression.
It returns the last element that satisfy the condition defined by the predicate expression. If not found then returns the default value for type T.

The following example finds the last element that matches with «Bill».

string[] names = { "Steve", "Bill", "Bill Gates", "Ravi", "Mohan", "Salman", "Boski" };
var stringToFind = "Bill";
 
var result = Array.FindLast(names, element => element.Contains(stringToFind)); // returns "Boski"

The following example returns the last element that starts with «B».

string[] names = { "Steve", "Bill", "James", "Mohan", "Salman", "Boski" };
 
var result = Array.FindLast(names, element => element.StartsWith("B")); // returns Boski

The following example returns the first element, whose length is five or more.

string[] names = { "Steve", "Bill", "Bill Gates", "James", "Mohan", "Salman", "Boski" };

result = Array.FindLast(names, element => element.Length >= 5); // returns Boski

Thus, choose the appropriate method as per your requirement to search for an element in an array in C#.


  1. Get Index of an Element in an Array With the Array.IndexOf() Function in C#
  2. Get Index of an Element in an Array With the Array.FindIndex() Function in C#
  3. Check for an Element in an Array With the Array.Exists() in C#

Check if an Array Contains a Value in C#

This tutorial will introduce methods to check for an element inside an array in C#.

Get Index of an Element in an Array With the Array.IndexOf() Function in C#

The C# Array.IndexOf(array, element) function gets the index of the element element inside the array array. It returns -1 if the element is not present in the array.

The following code example shows us how we can get the index of an element in an array with the Array.Indexof() function in C#.

using System;

namespace check_element_in_array
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] stringArray = { "value1", "value2", "value3", "value4" };
            string value = "value3";
            int index = Array.IndexOf(stringArray, value);
            if (index > -1)
            {
                Console.WriteLine("{0} found in the array at index {1}", value, index);
            }
            else
            {
                Console.WriteLine("Value not found");
            }
        }
    }
}

Output:

value3 found in the array at index 2

We displayed the index of the element value3 inside the array stringArray with the Array.IndexOf() function in C#. The above code displays the index of the element if the value is found and displays value not found if the value is not found in the array.

Get Index of an Element in an Array With the Array.FindIndex() Function in C#

The Array.FindIndex(array, pattern) function gets the index of the element that matches the pattern pattern inside the array array in C# if the element is present in the array. It returns -1 if the element is not present in the array. We can use lambda expressions to specify the pattern parameter in the Array.FindIndex() function.

The following code example shows us how we can get the index of an element in an array with the Array.FindIndex() function and lambda expressions in C#.

using System;

namespace check_element_in_array
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] stringArray = { "value1", "value2", "value3", "value4" };
            string value = "value3";
            var index = Array.FindIndex(stringArray, x => x == value);
            if (index > -1)
            {
                Console.WriteLine("{0} found in the array at index {1}", value, index);
            }
            else
            {
                Console.WriteLine("Value not found");
            }
        }
    }
}

Output:

value3 found in the array at index 2

We displayed the index of the element value3 inside the array stringArray with the Array.IndexOf() function in C#. The above code displays the index of the element if the value is found and displays value not found if the value is not found in the array.

Check for an Element in an Array With the Array.Exists() in C#

If we only need to check whether an element exists in an array and we are not concerned with the index of the array where the element is located, we can use the Array.Exists() function in C#. The Array.Exists() function returns a boolean value that is true if the element exists in the array and false if it does not exist in the array.

The following code example shows us how we can check for an element in an array with the Array.Exists() function in C#.

using System;

namespace check_element_in_array
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] stringArray = { "value1", "value2", "value3", "value4" };
            string value = "value3";
            var check = Array.Exists(stringArray, x => x == value);
            if (check == true)
            {
                Console.WriteLine("{0} found in the array", value);
            }
            else
            {
                Console.WriteLine("Value not found");
            }
        }
    }
}

Output:

value3 found in the array

In the above code, we checked whether the value value3 exists in the array stringArray with the Array.Exists() function in C#.

Like this post? Please share to your friends:
  • Find word from picture
  • Find word from other words
  • Find word from letters program
  • Find word from given letter
  • Find word for a new beginning