Check if string contains a number c# - c#

I know that there is lots of questions like this out there.
But I really couldn't find anything that solved my problem.
I want to check if the string contains the specific input number. See the following example:
public Boolean checkString()
{
string input = "2.5.8.12.30";
string intToFind = "3";
if (input.contains(intToFind))
{
return true;
}
else
{
return false;
}
}
This returns true but I want it to return false since the intToFind string is 3 and not 30. So it is the contains() that is the problem.
How do I make it search for 3 only?

You could use String.Split + Contains:
bool contains3 = input.Split('.').Contains("3");

bool anyThree = input.Split('.').Any(str => str == "3");

You may split your input using String.Split('.') into an array. Now use Array.contains to check if the element is within the array
bool contained = input.Split('.').Contains("3");

string[] words = input.Split('.');
if (words.contains("3")){do something...}

You could also use Regex which might be a little overkill.
string str = "2.5.8.12.30";
string strToFind = "3";
bool contains = Regex.Match(str, string.Format(#"\W{0}\W",strToFind)).Success;

Related

C# string comparision error

I am trying to check if value exists in a string array. The below one works but when I tried the next code block, it failed.
bool exixts;
string toCheck= "jupiter";
string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
if(printer.Contains(toCheck))
{
exists = true;
}
How can I check for trim and case sensitivity?
I tried this
bool exixts;
string toCheck= "jupiter ";
string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
if(printer.Contains(toCheck.Trim(),StringComparison.InvariantCultureIgnoreCase)))
{
exists = true;
}
The IEnumerable<string>.Contains(value, comparer) expects a compare class instance, not an enum value.
The library does have some ready made comparers available though:
//if(printer.Contains(toCheck.Trim(),StringComparison.InvariantCultureIgnoreCase)))
if (printer.Contains(toCheck.Trim(), StringComparer.OrdinalIgnoreCase))
Or you can do like this,
bool exists = printer.Any(x=> x == toCheck.Trim());
Hope helps,

Replace a substring

I have an input string. I need to replace its prefix (until first dot) with an other string.
The method signature:
string MyPrefixReplace(string input, string replacer)
Examples:
string res = MyPrefixReplace("12.345.6789", "000")
res = "000.345.6789";
res = MyPrefixReplace("908.345.6789", "1")
res = "1.345.6789";
Is there a way not to extract a sub-string before first dot and make a Replace**?
I.e - I don't want this solution
int i = input.IndexOf(".");
string rep = input.Substring(0,i);
input.Replace(rep,replacer);
Thanks
You could use String.Split
public string MyPrefixReplace(string source, string value, char delimiter = '.')
{
var parts = source.Split(delimiter);
parts[0] = value;
return String.Join(delimiter.ToString(), parts);
}
Live demo
Using String.IndexOf and String.Substring ist the most efficient way. In your approach you have used the wrong overload of Substring. String.Replace is pointless anyway since you don't want to replace all occurences of the first part but only the first part.
Therefore you don't have to take but to skip the the first part and prefix another. This works as desired:
public static string MyPrefixReplace(string input, string replacer, char prefixChar = '.')
{
int index = input.IndexOf(prefixChar);
if (index == -1)
return input;
return replacer + input.Substring(index);
}
Your input:
string result = MyPrefixReplace("908.345.6789", "1"); // 1.345.6789
result = MyPrefixReplace("12.345.6789", "000"); // 000.345.6789
Personally, I'd split the string up to get around this problem, although there's obviously other ways of doing this, this would be my approach:
string Input = "123.456.789"
string[] SplitInput = Input.Split('.');
SplitInput[0] = "321";
string Output = String.Join('.', SplitInput);
Output should be "321.456.789".

How to check if a string contains a particular letter/symbol/number in C#?

string text = "Tag*";
I want check if my string contains * or not.
How do I check this in C#?
You can use String.IndexOf or String.Contains to find if string contains particular string. If you have single character to search you can using String.IndexOf Method (Char)
if(text.IndexOf("*") > -1)
{
}
Return Value Type: System.Int32 The zero-based index position of value
if that string is found, or -1 if it is not. If value is String.Empty,
the return value is 0, MSDN
I dont know how come you dont know this..or how much you googled it but it can be done as follows:
text.Contains("*");
Try Following :
string text = "Tag*";
if(text.Contains("*"))
{
//true
}
else
{
//false
}
You can try the Contains extension to check whether the string contains specific string
string yourText = "abcd*efg";
bool containStar = yourText.Contains("*");
string[] sArray = new string[] { "*" };
string stringToCheck = "Tag*";
bool iscontain = sArray.Any(stringToCheck.Contains);

Is there a way to evaluate more than one string inside of a string.contains() method?

if (description.ToUpper().Contains("BOUGHT") || description.ToUpper().Contains("PURCHASE"))
The code above is what I have and I wondered if I had a longer list of strings for the same condition, how I would do it without making the code too long. Maybe a lambda expression?
No, there is no built in function. But it's not hard to write it yourself:
string[] needles = new string[]{"BOUGHT", "PURCHASE"};
string haystack = description.ToUpperInvariant();
bool found = needles.Any(needle=> haystack.Contains(needle));
I only convert hackstack to upper once to improve performance.
Alternatively you could use IndexOf(needle, StringComparison.OrdinalIgnoreCase)>=0:
string[] needles = new string[]{"BOUGHT", "PURCHASE"};
string haystack = description;
bool found = needles.Any(needle=> haystack.IndexOf(needle, StringComparison.OrdinalIgnoreCase)>=0);
You should not use ToUpper() here, since that uses the current culture. Using the current culture can lead to unexpected problems on some computers, for example i does not uppercase to I when using the Turkish culture.
There might still some subtle problems remaining where ToUpperInvariant() on both sides and a case insensitive comparison might return different results, but that's only relevant if you have unusual characters in both your haystack and needles.
You can rework the code to something like this:
var words = new[] { "BOUGHT", "PURCHASE" };
var desc = description.ToUpper();
if(words.Any(w => description.Contains(w)) {
// something matched
}
if (someCollectionOfStrings.Any(string => originalString.Contains(string))
{
//stuff
}
Use a regular expression:
if (Regex.IsMatch(description, "purchase|bought", RegexOptions.IgnoreCase)) {
// ...
}
Regex.IsMatch(input, string.Join("|", strings));
You might have to escape the strings if they contain Regex control characters.
public static bool ContainsOneOfManyIgnoreCase(this string str, params string [] items)
{
return items.Any(x => str.IndexOf(x, StringComparison.CurrentCultureIgnoreCase) != -1);
}

string manipulation check and replace with fastest method

I have some strings like below:
string num1 = "D123_1";
string num2 = "D123_2";
string num3 = "D456_11";
string num4 = "D456_22";
string num5 = "D_123_D";
string num5 = "_D_123";
I want to make a function that will do the following actions:
1- Checks if given string DOES HAVE an Underscore in it, and this underscore should be after some Numbers and Follow with some numbers: in this case 'num5' and 'num6' are invalid!
2- Replace the numbers after the last underscore with any desired string, for example I want 'num1 = "D123_1"' to be changed into 'D123_2'
So far I came with this idea but it is not working :( First I dont know how to check for criteria 1 and second the replace statement is not working:
private string CheckAndReplace(string given, string toAdd)
{
var changedString = given.Split('_');
return changedString[changedString.Length - 1] + toAdd;
}
Any help and tips will be appriciated
What you are looking for is a regular expression. This is (mostly) from the top of my head. But it should easily point you in the right direction. The regular expression works fine.
public static Regex regex = new Regex("(?<character>[a-zA-Z]+)(?<major>\\d+)_(?<minor>\\d+)",RegexOptions.CultureInvariant | RegexOptions.Compiled);
Match m = regex.Match(InputText);
if (m.Succes)
{
var newValue = String.Format("{0}{1}_{2}"m.Groups["character"].Value, m.Groups["major"].Value, m.Groups["minor"].Value);
}
In your code you split the String into an array of strings and then access the wrong index of the array, so it isn't doing what you want.
Try working with a substring instead. Find the index of the last '_' and then get the substring:
private string CheckAndReplace(string given, string toAdd) {
int index = given.LastIndexOf('_')+1;
return given.Substring(0,index) + toAdd;
}
But before that check the validity of the string (see other answers). This code fragment will break when there's no '_' in the string.
You could use a regular expression (this is not a complete implementation, only a hint):
private string CheckAndReplace(string given, string toAdd)
{
Regex regex = new Regex("([A-Z]*[0-9]+_)[0-9]+");
if (regex.IsMatch(given))
{
return string.Concat(regex.Match(given).Groups[1].Value, toAdd);
}
else
{
... do something else
}
}
Use a good regular expression implementation. .NET has standard implementation of them

Categories