Check String of chars - c#

I'm looking for an fast method-solutions of my Problem to check a String, if this contains an min one char. IF String contains like any one of character in alphabet then return true, else false.
public bool checkString(String s)
{
return true || false;
}
For Example:
"1232133432454355467" return false
"134324239846c" return true

Try:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
var r = CheckString("112");
Console.WriteLine(r); // false
r = CheckString("112a");
Console.WriteLine(r); // true
}
public static bool CheckString(String input)
{
return Regex.Match(input, #"[a-zA-Z]").Success;
// or, as #Vlad L suggested
//return Regex.IsMatch(input, #"[a-zA-Z]");
}
}
If you want to verify against the "All Letters" Unicode character class, use this one instead:
return Regex.IsMatch(input, #"\p{L}");
Reference: Supported Unicode General Categories

If I understood the question correctly... This returns true if the string contains at least one letter.
public bool checkString(String s)
{
return s.Any(x => Char.IsLetter(x));
}

Try this with ToCharArray():
public bool checkString(String s)
{
bool retValue = s.ToCharArray()
.Any(c => ((int)c > 64 && (int)c < 91) ||
((int)c > 96 && (int)c < 123));
return retValue
}

Just for sake of completion.
// Regex to check the value consists of letters
// with atleast 1 character
private static Regex reg = new Regex(#"[a-zA-Z]+");
public bool checkString(String s)
{
return reg.Match(s).Success;
}

What about this?
if (Regex.IsMatch(yourString, "[a-zA-Z]"))
{
}

static void Main(string[] args)
{
Console.WriteLine(checkString("137563475634c756"));
}
static public bool checkString(String s)
{
return Regex.IsMatch(s, "[a-zA-Z]");
}
It Returns True.

Related

c# get substring of enum value

Is there a clever way to get an enum value by comparing a substring a la String.Contains with the enum?
I checked this implementation (Convert a string to an enum in C#), but would like to have an intelligent extension doing the same but including substrings comparison, something like TryParse with an option to check the whole substring of the enum values.
public static void Main()
{
string a = "HANS";
GetName(a); // prints Hans
string a1 = "Peter";
GetName(a1); // should print enum value "WolfgangPeterDietrich " containing the substring "Peter"
}
public enum MyNames
{
Hans = 0,
WolfgangPeterDietrich = 3,
}
public static void GetName(string a)
{
MyNames dif;
// this works fine, ignore case
if (Enum.TryParse(a, true, out dif))
{
System.Console.WriteLine(dif.ToString());
}
// ToDo: check for substring ??
}
This approach takes the first occurrence found, and is case insensitive.
public static void GetName(string a)
{
string? result = Enum.GetNames<MyNames>()
.FirstOrDefault(x => x.Contains(a, StringComparison.OrdinalIgnoreCase));
System.Console.WriteLine(result);
}
Just a prototype to fix with boundary cases and assertions:
public static T EnumNameContains<T>(string substringOfName) where T: struct
{
return (T)Enum.Parse(typeof(T),
Enum.GetNames(typeof(T)).FirstOrDefault(
name => name.IndexOf(substringOfName,StringComparison.CurrentCultureIgnoreCase) >= 0));
}
I guess can help.
You can try this
public static void GetName(string a)
{
MyNames dif;
// this works fine, ignore case
if (Enum.TryParse(a, true, out dif))
{
System.Console.WriteLine(dif.ToString());
}
else
{
var result = Enum.GetNames(typeof(MyNames)).Where(dd => dd.Contains(a, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
System.Console.WriteLine(result);
}
}

c# compare strings with a comparison function

I may be missing the obvious but how do I provide a compare function to string.Equals() ?
I need to test for string equality but allow the first letter to be of a different case, so StringComparison is not useful, but I can't see a way to provide my own function to string.Equals ?
var s1="John";
var s2="john";
if (string.Equals(s1, s2, ????)) console.Write("Equal!!");
The Equals method does not have an overload that takes a custom compare function, but you could write one as an extension method:
public static class Extensions
{
public static bool EqualsCaseExceptFirst(this string input, string other)
{
if (input == null) throw new NullReferenceException();
if (ReferenceEquals(input, other)) return true;
if (input.Length != other.Length) return false;
if (input.Length == 0) return true;
if (!input.Substring(0, 1).Equals(other.Substring(0, 1),
StringComparison.OrdinalIgnoreCase)) return false;
return input.Length == 1 || input.Substring(1).Equals(other.Substring(1));
}
}
A sample test might look like:
private static void Main()
{
var testStrings = new List<string>
{
"hello", "Hello", "HELLO", "hELLO"
};
var sample = "Hello";
foreach (var testString in testStrings)
{
var result = sample.EqualsCaseExceptFirst(testString);
Console.WriteLine($"'{sample}' == '{testString}' : {result}");
}
Console.WriteLine("----------");
sample = "HELLO";
foreach (var testString in testStrings)
{
var result = sample.EqualsCaseExceptFirst(testString);
Console.WriteLine($"'{sample}' == '{testString}' : {result}");
}
GetKeyFromUser("\nDone! Press any key to exit...");
}
Output
You mentioned in the comments that you want to create an IEqualityComparer class, so here's a sample that simply reuses this method:
class CustomComparer : IEqualityComparer<string>
{
public bool Equals(string first, string second)
{
return first?.EqualsCaseExceptFirst(second) ?? false;
}
public int GetHashCode(string obj)
{
return obj?.GetHashCode() ?? 0;
}
}
You could just roll your own, add pepper and salt to taste
public static bool MyStringEquals(this string str1, string str2, StringComparison comparison = StringComparison.CurrentCulture)
=> !(str1?.Length > 0) || !(str2?.Length > 0) || string.Equals(str1.Substring(1), str2.Substring(1),comparison);
Usage
var s1 = "asd";
var s2 = "bsd";
var result = s1.MyStringEquals(s2, StringComparison.Ordinal);
Obviously, you will want to write yourself a bunch of test cases, and work out if this is what you want

Regex or loop in loop

I have a function: bool ContainsOneOf(string str1, string validchars) which get 2 strings and checks if one of the letters in one string is in the other string.
Here's the code:
public static bool ContainsOneOf(string str1, string validchars)
{
foreach (char ch in str1)
{
foreach (char ch2 in validchars)
{
if (ch == ch2)
{
return true;
}
}
}
return false;
}
Other way to write it by using regex:
public static bool ContainsOneOf(string str1, string validchars)
{
return Regex.IsMatch(str1, #"[" + validchars + "]");
}
Which way should I use? (efficient)
Regex.IsMatch has too much overhead, I would use Enumerable.Any:
static bool ContainsOneOf(string str1, string validchars)
{
return str1.Any(c => validChars.Contains(c));
}
I suggest using linq:
public static bool ContainsOneOf(string str1, string validchars)
{
return str1.Any(ch => validchars.Any(ch2 => ch == ch2));
}
Or
public static bool ContainsOneOf(string str1, string validchars)
{
return (from ch in str1 from ch2 in validchars where ch == ch2 select ch).Any();
}
Just a variation to the other answers: I would switch str1 and validChars in the check, and also change the type of validChars to IEnumerable as to make it more reusable. Also, making it an extension method makes sense.
static bool ContainsOneOf(this string str1, IEnumerable<char> validchars)
{
return validchars.Any(c => str1.Contains(c));
}
An alternative to the other answers posted so far:
public static bool ContainsOneOf(string str1, string validchars)
{
return str1.IndexOfAny(validchars.ToCharArray()) != -1;
}
More on String.IndexOfAny:
https://msdn.microsoft.com/en-us/library/system.string.indexofany(v=vs.110).aspx

C# : Search the "v" which may or may not occur in the end of the string

So, I have a C# string input which can be either "ABCD12345678" or "ABCD1234" or "ABCD1233456v1" or "ABCD1233456v2" or "AVVV1233456v334" or "ABVV1233456V4".
I need to manipulate and remove the last may or may not be occurring "v"/"V" and get the result like :
"ABCD1233456"
"ABVV1233456"
"AVVV1233456"
Please help. If I use substring straightforward it works for only those where "v" occurs but throws exception for those where it doesn't occur.
It's a little confusing when you say at the end because the v isn't really at the end...
Anyway, what about Regex?
public static class VRemover
{
public static string Process(string input)
{
var regex = new Regex(#"(?'util'[a-z]+\d+)(v\d*)?", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
return regex.IsMatch(input)
? regex.Match(input).Groups["util"].Value
: input;
}
}
You can validate with this test (NUnit):
[TestFixture]
public class VRemoverTests
{
[Test]
public void Test()
{
var inputs = new[]
{
"ABCD12345678",
"ABCD1234",
"ABCD1233456v1",
"ABCD1233456v2",
"AVVV1233456v334",
"ABVV1233456V4"
};
var expecteds = new[]
{
"ABCD12345678",
"ABCD1234",
"ABCD1233456",
"ABCD1233456",
"AVVV1233456",
"ABVV1233456"
};
for (var i = 0; i < inputs.Length; i++)
{
var actual = VRemover.Process(inputs[i]);
Assert.AreEqual(expecteds[i], actual);
}
}
}
private static string RemoveString (string input)
{
var indexOf = input.LastIndexOf("v", StringComparison.OrdinalIgnoreCase);
if (indexOf < 0)
return input;
return input.Substring(0, indexOf);
}
private string ReplaceLastV(string input)
{
if (input.IndexOf("v", StringComparison.OrdinalIgnoreCase) > 0)
{
int lastIndexV = input.LastIndexOf("v", StringComparison.OrdinalIgnoreCase);
return input.Substring(0, lastIndexV);
}
return input;
}

Why is this producing a Null Value Exception?

The exception I get is:
The type initializer for MyNamespace.Program threw an exception
The inner exception says
Message: Value cannot be null. Parameter name: collection
Source: ... HashSet ...
This leads me to believe the error is occuring on the line indicated below...
class Program
{
public static IEnumerable<char> WordCharacters = ExpandCharacterSet("A-Za-z0-9_");
public static IEnumerable<char> NonWordCharacters = ExpandCharacterSet("^A-Za-z0-9_");
public static IEnumerable<char> SpaceCharacters = ExpandCharacterSet(" \f\n\r\t\v");
public static IEnumerable<char> NonSpaceCharacters = ExpandCharacterSet("^ \f\n\r\t\v");
public static IEnumerable<char> DigitCharacters = ExpandCharacterSet("0-9");
public static IEnumerable<char> NonDigitCharacters = ExpandCharacterSet("^0-9");
public static IEnumerable<char> WildCharacters = ExpandCharacterSet("^\n");
public static IEnumerable<char> AllCharacters = Enumerable.Range(0, 256).Select(Convert.ToChar).Where(c => !char.IsControl(c));
public static IEnumerable<char> ExpandCharacterSet(string set)
{
if (set.Length == 0)
return "";
var sb = new StringBuilder();
int start = 0;
bool invertSet = false;
if (set[0] == '[' && set[set.Length - 1] == ']')
set = set.Substring(1, set.Length - 2);
if (set[0] == '^')
{
invertSet = true;
set = set.Substring(1);
}
set = Regex.Unescape(set);
foreach (Match m in Regex.Matches(set, ".-.|."))
{
if (m.Value.Length == 1)
sb.Append(m.Value);
else
{
if (m.Value[0] > m.Value[2]) throw new ArgumentException("Invalid character set.");
for (char c = m.Value[0]; c <= m.Value[2]; ++c)
sb.Append(c);
}
}
if (!invertSet) return sb.ToString();
var A = new HashSet<char>(AllCharacters); // <---- change this to "ABC" and the error goes away
var B = new HashSet<char>(sb.ToString());
A.ExceptWith(B);
return A;
}
static void Main(string[] args)
{
}
}
But I don't know why. When I print the chars,
Console.WriteLine(string.Concat(AllChars));
It prints every character as expected. So why does HashSet think it's null?
I'm guessing that ExpandCharacterSet is being used to initialize another static field. There's no guarantee on the order in which two static fields will be initialized, and so presuably, it's trying to initialize the other field before it initializes AllChars.
Try moving the assignments into an explicit static constructor, with the correct initialization order.
e.g if your current code has:
public static IEnumerable<char> AllChars = Enumerable.Range(0, 256).Select(Convert.ToChar).Where(c => !char.IsControl(c));
public static IEnumerable<char> Expanded = ExpandCharacterSet(...);
Make it instead:
public static IEnumerable<char> AllChars;
public static IEnumerable<char> Expanded;
static <ClassName> {
AllChars = Enumerable.Range(0, 256).Select(Convert.ToChar).Where(c => !char.IsControl(c));
Expanded = ExpandCharacterSet(...);
}
I think, AllChars is being set to null from some other part of your code, because the above two methods seems to be working fine.
Can you provide some more details of implementation.
I'm not getting any except on based on the following two lines of code. Where is the line of code that is throwing the exception?
public static IEnumerable<char> AllChars = Enumerable.Range(0, 256)
.Select(Convert.ToChar)
.Where(c => !char.IsControl(c));
var A = new HashSet<char>(AllChars);

Categories