0

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

1
  • Are you sure that str is the most logical way to be holding this data? Why are you not using some collection type which can hold multiple values? Commented Jul 25, 2014 at 9:52

6 Answers 6

3

You can split the string into array and then check like this

bool bFound = str.split('|').Contains("p1")
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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

Comments

0
str.Split('|').Contains("P1");

Comments

0

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

Comments

0

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)");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.