Reputation: 97
I've a string looking like this : str = P1|P2|P3....
I need to check if the string contains for instance P1. I do that :
if (str.Contains("P1"))
{...}
My issue comes when I look for P1 and str does not contains P1 but P10, it returns true, which is logical, but not what I need.
How can I check strictly for P1 without returning true if I have P10 in the string.
Thanks for your help
Upvotes: 0
Views: 706
Reputation: 31
You have to check if string you are looking for is followed by '|' or is at the end of the string in which you check.
String str = "P1|P3|P20";
String strToFind = "P2";
System.Text.RegularExpressions.Regex.IsMatch(str, strToFind+@"(\||\Z)");
Upvotes: 0
Reputation: 1832
Might be a good case for using a regex, as you need to make sure that the string you are looking for is delimited by either a pipe or the end of the string.
For example:
string input = "P1|P2|P3|P10";
string pattern = @"P1(\||$)";
Regex.IsMatch(input, pattern);
Upvotes: 0
Reputation: 354536
If you need to check for P10
as well, then do so in reverse order, which means you'd pick up P10
before P1
.
If every Psomething
is followed by a |
you can check for P1|
. This won't work if it's a separator and won't appear at the very end of the string.
A regex would be another solution:
Regex.IsMatch(str, "P1(?!\d)") // Matches P1 if not followed by another digit
Generally, if you run into this problem, it's a poor choice of data structures, though. A string isn't exactly a collection of things and that's what you're trying to model here.
Upvotes: 2
Reputation: 4963
You can split the string into array and then check like this
bool bFound = str.split('|').Contains("p1")
Upvotes: 3
Reputation: 28107
Why not split the string and check against that:
string input = "P1|P2|P3|P10";
string[] split = input.Split('|'); // { "P1", "P2", "P3", "P10" }
bool containsP1 = split.Contains("P1"); // true
Upvotes: 1