Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string contains some part of another string in C#?

Tags:

string

c#

String1 = "12345"
String2 = "12abc"

I want to return true if String1 contains some part of String2. In this example String2 has "12" which exists in String1. So For example String1.Contains(String2) should return true.

How Can I make such 'Contains' Function?

like image 643
Inside Man Avatar asked Apr 10 '16 06:04

Inside Man


People also ask

How do you check if a string is substring of another string in C?

The function strstr returns the first occurrence of a string in another string. This means that strstr can be used to detect whether a string contains another string. In other words, whether a string is a substring of another string.

How do you check if two strings are substring of each other?

just compare the 2 with '==='. If the two strings are abc and cde , should they be considered "identical" because of c ? if you know what the substring is, you can perform indexOf on both the strings to check if the substring exists.

Is there a substring function in C?

So it turns out that, in C, it's actually impossible to write a proper "utility" substring function, that doesn't do any dynamic memory allocation, and that doesn't modify the original string. All of this is a consequence of the fact that C does not have a first-class string type.

How do you check if a string contains some part of another string C#?

The C# Contains() method is used to return a value indicating whether the specified substring occurs within this string or not. If the specified substring is found in this string, it returns true otherwise false.


1 Answers

You haven't told us the minimum length of the matching string, so I'll assuming the minimum length is 1.

Therefore, you can write:

String1.Any(c => String2.Contains(c))
like image 72
Rob Avatar answered Oct 12 '22 22:10

Rob