Is there a variant of this?
if (blabla.Contains("I'm a noob") | blabla.Contains("sry") | blabla.Contains("I'm a noob "+"sry"))
{
//stuff
}
like:
if (blabla.Contains("I'm a noob) and/or ("sry")
{
//stuff
}
Help is appreciated!
You can't collapse it quite as far as you asked, but you can do:
if (blabla.Contains("I'm a noob") || blabla.Contains("sry"))
{
//stuff
}
The "and" case is handled here because a string with both would actually pass both of the statements in the "Or".
As far as I'm aware, there are no built-in methods to do this. But with a little LINQ and extension methods, you can create your own methods that will check to see if a string contains any or all tokens:
public static class ExtensionMethods{
public static bool ContainsAny(this string s, params string[] tokens){
return tokens.Any(t => s.Contains(t));
}
public static bool ContainsAll(this string s, params string[] tokens){
return tokens.All(t => s.Contains(t));
}
}
You could use it like this (remember, params arrays take a variable number of parameters, so you're not limited to just two like in my example):
var str = "this is a string";
Console.WriteLine(str.ContainsAny("this", "fake"));
Console.WriteLine(str.ContainsAny("doesn't", "exist"));
Console.WriteLine(str.ContainsAll("this", "is"));
Console.WriteLine(str.ContainsAll("this", "fake"));
Output:
True
False
True
False
Edit:
For the record, LINQ is not necessary. You could just as easily write them this way:
public static class ExtensionMethods{
public static bool ContainsAny(this string s, params string[] tokens){
foreach(string token in tokens)
if(s.Contains(token)) return true;
return false;
}
public static bool ContainsAll(this string s, params string[] tokens){
foreach(string token in tokens)
if(!s.Contains(token)) return false;
return true;
}
}
var arr = new[]{"I'm a noob" ,"sry", "I'm a noob +sry"};
if(arr.Any(x => blabla.Contains(x)))
{
}
You can use a regex:
Regex r = new Regex("I'm a noob|sry|I'm a noob sry");
if(r.IsMatch(blabla)) {
//TODO: do something
}
Regular expressions have other advanced features like: a* matches with the empty string, a, aa, aaa,...
The funny part is that if you "compile" the regex (for instance using new Regex("I'm a noob|sry|I'm a noob sry",RegexOptions.Compiled), C# will turn it automatically into the fastest solution mechanism possible. For instance if blabla is a 100k chars string, you will only run once over the entire string. And for instance redundant parts like I'm a noob sry will be omitted automatically.
Related
I would like to display names in title case and also convert the hyphenated names — such as O'Reilly — properly.
Right now, when I use the ToUpperCase function, I get "O'reilly", and that is not what I want.
Here's the function I am using:
#functions
{
public static class TextConvert
{
public static string ToTitleCase(string s)
{
s = s.ToLower();
return Regex.Replace(s, #"(^\w)|(\s\w)",b => b.Value.ToUpper());
}
}
}
How can I do that, accounting for cases like O'Reilly?
You can try It.
var titlecase = PrintName("o'riley");
Call this function
Public static string PrintName(string StrValue)//pass here - o'riley
{
if (!string.IsNullOrEmpty(StrValue))
{
return Regex.Replace(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(StrValue.ToLower()),
"['-](?:.)", m => m.Value.ToUpperInvariant());
}
else
{
return "Something meaningful message";
}
}
You can't do this with technical tools alone. There are African names that do not start with a capital letter at all. As you can see in this utility (http://www.johncardinal.com/tmgutil/capitalizenames.htm), the easiest way out is to actually maintain a list of exceptions and match your name against it.
How do I check a string to make sure it contains numbers, letters, or space only?
In C# this is simple:
private bool HasSpecialChars(string yourString)
{
return yourString.Any(ch => ! char.IsLetterOrDigit(ch));
}
The easiest way it to use a regular expression:
Regular Expression for alphanumeric and underscores
Using regular expressions in .net:
http://www.regular-expressions.info/dotnet.html
MSDN Regular Expression
Regex.IsMatch
var regexItem = new Regex("^[a-zA-Z0-9 ]*$");
if(regexItem.IsMatch(YOUR_STRING)){..}
string s = #"$KUH% I*$)OFNlkfn$";
var withoutSpecial = new string(s.Where(c => Char.IsLetterOrDigit(c)
|| Char.IsWhiteSpace(c)).ToArray());
if (s != withoutSpecial)
{
Console.WriteLine("String contains special chars");
}
Try this way.
public static bool hasSpecialChar(string input)
{
string specialChar = #"\|!#$%&/()=?»«#£§€{}.-;'<>_,";
foreach (var item in specialChar)
{
if (input.Contains(item)) return true;
}
return false;
}
String test_string = "tesintg#$234524##";
if (System.Text.RegularExpressions.Regex.IsMatch(test_string, "^[a-zA-Z0-9\x20]+$"))
{
// Good-to-go
}
An example can be found here: http://ideone.com/B1HxA
If the list of acceptable characters is pretty small, you can use a regular expression like this:
Regex.IsMatch(items, "[a-z0-9 ]+", RegexOptions.IgnoreCase);
The regular expression used here looks for any character from a-z and 0-9 including a space (what's inside the square brackets []), that there is one or more of these characters (the + sign--you can use a * for 0 or more). The final option tells the regex parser to ignore case.
This will fail on anything that is not a letter, number, or space. To add more characters to the blessed list, add it inside the square brackets.
Use the regular Expression below in to validate a string to make sure it contains numbers, letters, or space only:
[a-zA-Z0-9 ]
You could do it with a bool. I've been learning recently and found I could do it this way. In this example, I'm checking a user's input to the console:
using System;
using System.Linq;
namespace CheckStringContent
{
class Program
{
static void Main(string[] args)
{
//Get a password to check
Console.WriteLine("Please input a Password: ");
string userPassword = Console.ReadLine();
//Check the string
bool symbolCheck = userPassword.Any(p => !char.IsLetterOrDigit(p));
//Write results to console
Console.WriteLine($"Symbols are present: {symbolCheck}");
}
}
}
This returns 'True' if special chars (symbolCheck) are present in the string, and 'False' if not present.
A great way using C# and Linq here:
public static bool HasSpecialCharacter(this string s)
{
foreach (var c in s)
{
if(!char.IsLetterOrDigit(c))
{
return true;
}
}
return false;
}
And access it like this:
myString.HasSpecialCharacter();
private bool isMatch(string strValue,string specialChars)
{
return specialChars.Where(x => strValue.Contains(x)).Any();
}
Create a method and call it hasSpecialChar with one parameter
and use foreach to check every single character in the textbox, add as many characters as you want in the array, in my case i just used ) and ( to prevent sql injection .
public void hasSpecialChar(string input)
{
char[] specialChar = {'(',')'};
foreach (char item in specialChar)
{
if (input.Contains(item)) MessageBox.Show("it contains");
}
}
in your button click evenement or you click btn double time like that :
private void button1_Click(object sender, EventArgs e)
{
hasSpecialChar(textbox1.Text);
}
While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:
Add the [https://www.nuget.org/packages/Extensions.cs][1] package to your project.
Add "using Extensions;" to the top of your code.
"smith23#".IsAlphaNumeric() will return False whereas "smith23".IsAlphaNumeric() will return True. By default the .IsAlphaNumeric() method ignores spaces, but it can also be overridden such that "smith 23".IsAlphaNumeric(false) will return False since the space is not considered part of the alphabet.
Every other check in the rest of the code is simply MyString.IsAlphaNumeric().
Based on #prmph's answer, it can be even more simplified (omitting the variable, using overload resolution):
yourString.Any(char.IsLetterOrDigit);
No special characters or empty string except hyphen
^[a-zA-Z0-9-]+$
i have faced this question in interview as below?
let us consider the string named
string gowtham="test1,test2,test3" ;
i need to convert in to IEnumerable string function
i need a output to be as
new[] {"test1", "test2","test3" }
what i did is i have created a string() function by spliting values by comma seperated as below
string[] mysamples= gowtham.Split(',');
i do not know how to proceed after
waiting for your responses?
Every array is already a IEnumerable, in your case if you want to explicit cast to one IEnumerable of string you could use
IEnumerable<string> mysamplesEnumerable = mysamples as IEnumerable<string>
if you interviewer wanted a function that did this you could do
IEnumerable<string> SplitEnumByComa(string input)
{
return input.Split(',');
}
If I understand your question clearly, you can use a method like this;
public static IEnumerable<string> YourMethod()
{
string gowtham = "test1,test2,test3";
string[] mysamples = gowtham.Split(',');
List<string> senum = new List<string>();
foreach ( string s in mysamples )
{
senum.Add(s);
}
return senum as IEnumerable<string>;
}
Since string[] implements IEnumerable<T> interface, it seems you just need to cast it as IEnumerable<T>
EDIT: Since Magnus and LukeH warned me, there is an easy way also what you want to do.
public static IEnumerable<string> YourMethod()
{
string gowtham = "test1,test2,test3";
return gowtham .Split(',');
}
What is the smallest amount of C# possible to Check that a String fits this format #-##### (1 number, a dash then 5 more numbers).
It seems to me that a regular expression could do this quick (again, I wish I knew regular expressions).
So, here is an example:
public bool VerifyBoxNumber (string boxNumber)
{
// psudo code
if (boxNumber.FormatMatch("#-#####")
return true;
return false;
}
If you know real code that will make the above comparison work, please add an answer.
private static readonly Regex boxNumberRegex = new Regex(#"^\d-\d{5}$");
public static bool VerifyBoxNumber (string boxNumber)
{
return boxNumberRegex.IsMatch(boxNumber);
}
return Regex.IsMatch(boxNumber, #"^\d-\d{5}$");
^\d-\d{5}$ would be a regexp that matches only this pattern.
I am trying to create a generic formatter/parser combination.
Example scenario:
I have a string for string.Format(), e.g. var format = "{0}-{1}"
I have an array of object (string) for the input, e.g. var arr = new[] { "asdf", "qwer" }
I am formatting the array using the format string, e.g. var res = string.Format(format, arr)
What I am trying to do is to revert back the formatted string back into the array of object (string). Something like (pseudo code):
var arr2 = string.Unformat(format, res)
// when: res = "asdf-qwer"
// arr2 should be equal to arr
Anyone have experience doing something like this? I'm thinking about using regular expressions (modify the original format string, and then pass it to Regex.Matches to get the array) and run it for each placeholder in the format string. Is this feasible or is there any other more efficient solution?
While the comments about lost information are valid, sometimes you just want to get the string values of of a string with known formatting.
One method is this blog post written by a friend of mine. He implemented an extension method called string[] ParseExact(), akin to DateTime.ParseExact(). Data is returned as an array of strings, but if you can live with that, it is terribly handy.
public static class StringExtensions
{
public static string[] ParseExact(
this string data,
string format)
{
return ParseExact(data, format, false);
}
public static string[] ParseExact(
this string data,
string format,
bool ignoreCase)
{
string[] values;
if (TryParseExact(data, format, out values, ignoreCase))
return values;
else
throw new ArgumentException("Format not compatible with value.");
}
public static bool TryExtract(
this string data,
string format,
out string[] values)
{
return TryParseExact(data, format, out values, false);
}
public static bool TryParseExact(
this string data,
string format,
out string[] values,
bool ignoreCase)
{
int tokenCount = 0;
format = Regex.Escape(format).Replace("\\{", "{");
for (tokenCount = 0; ; tokenCount++)
{
string token = string.Format("{{{0}}}", tokenCount);
if (!format.Contains(token)) break;
format = format.Replace(token,
string.Format("(?'group{0}'.*)", tokenCount));
}
RegexOptions options =
ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None;
Match match = new Regex(format, options).Match(data);
if (tokenCount != (match.Groups.Count - 1))
{
values = new string[] { };
return false;
}
else
{
values = new string[tokenCount];
for (int index = 0; index < tokenCount; index++)
values[index] =
match.Groups[string.Format("group{0}", index)].Value;
return true;
}
}
}
You can't unformat because information is lost. String.Format is a "destructive" algorithm, which means you can't (always) go back.
Create a new class inheriting from string, where you add a member that keeps track of the "{0}-{1}" and the { "asdf", "qwer" }, override ToString(), and modify a little your code.
If it becomes too tricky, just create the same class, but not inheriting from string and modify a little more your code.
IMO, that's the best way to do this.
It's simply not possible in the generic case. Some information will be "lost" (string boundaries) in the Format method. Assume:
String.Format("{0}-{1}", "hello-world", "stack-overflow");
How would you "Unformat" it?
Assuming "-" is not in the original strings, can you not just use Split?
var arr2 = formattedString.Split('-');
Note that this only applies to the presented example with an assumption. Any reverse algorithm is dependent on the kind of formatting employed; an inverse operation may not even be possible, as noted by the other answers.
A simple solution might be to
replace all format tokens with (.*)
escape all other special charaters in format
make the regex match non-greedy
This would resolve the ambiguities to the shortest possible match.
(I'm not good at RegEx, so please correct me, folks :))
After formatting, you can put the resulting string and the array of objects into a dictionary with the string as key:
Dictionary<string,string []> unFormatLookup = new Dictionary<string,string []>
...
var arr = new string [] {"asdf", "qwer" };
var res = string.Format(format, arr);
unFormatLookup.Add(res,arr);
and in Unformat method, you can simply pass a string and look up that string and return the array used:
string [] Unformat(string res)
{
string [] arr;
unFormatLoopup.TryGetValue(res,out arr); //you can also check the return value of TryGetValue and throw an exception if the input string is not in.
return arr;
}