Home > OS >  Recommended way of checking if a certain string has a specified character more than once
Recommended way of checking if a certain string has a specified character more than once

Time:10-20

Firstly I understand that there are several ways to do this and I do have some code which runs, but what I just wanted to find out was if anyone else has a recommended way to do this. Say I have a string which I already know that would have contain a specific character (a ‘,’ in this case). Now I just want to validate that this comma is used only once and not more. I know iterating through each character is an option but why go through all that work because I just want to make sure that this special character is not used more than once, I’m not exactly interested in the count per se. The best I could think was to use the split and here is some sample code that works. Just curious to find out if there is a better way to do this. In summary, I have a certain string in which I know has a special character (‘,’ in this case) I want to validate that this special character has only been used once in this string

const char characterToBeEvaluated = ',';
string myStringToBeTested = "HelloWorldLetus,code";

var countOfIdentifiedCharacter = myStringToBeTested.Split(characterToBeEvaluated).Length - 1;

if (countOfIdentifiedCharacter == 1)
{
    Console.WriteLine("Used exactly once as expected");
}
else
{
    Console.WriteLine("Used either less than or more than once");
}

CodePudding user response:

You can use string's IndexOf methods:

const char characterToBeEvaluated = ',';
string myStringToBeTested = "HelloWorldLetus,code";

string substringToFind = characterToBeEvaluated.ToString();
int firstIdx = myStringToBeTested.IndexOf(substringToFind, StringComparison.Ordinal);
bool foundOnce = firstIdx >= 0;
bool foundTwice = foundOnce && myStringToBeTested.IndexOf(substringToFind, firstIdx   1, StringComparison.Ordinal) >= 0;

Try it online

CodePudding user response:

You could use the LINQ Count() method:

const char characterToBeEvaluated = ',';
string myStringToBeTested = "HelloWorldLetus,code";
var countOfIdentifiedCharacter = myStringToBeTested.Count(x => x == characterToBeEvaluated);

if (countOfIdentifiedCharacter == 1)
{
    Console.WriteLine("Used exactly once as expected");
}
else
{
    Console.WriteLine("Used either less than or more than once");
}

This is the most readable and simplest approach and is great if you need to know the exact count but for your specific case @ProgrammingLlama's answer is better in terms of efficiency.

  • Related