If else minifier - c#

I have many lines of code like this.. this is just a 1 thing i am trying right now.
if (RI2.Text.Contains("SOS") || RI2.Text.Contains("WAR"))
{
Response.Redirect("http://mydomain.com/rabat");
}
if (RI2.Text.Contains("sos") || RI2.Text.Contains("war"))
{
Response.Redirect("http://mydomain.com/rabat");
}
How do i minify this code. i mean, its very ugly and there many lines of code similar to this.
is there any better way of doing this which i dont know.
please help. appreciate your time and help.

Try this regular expression.
Ignores case in comparison (SOS and sos matched)
Does not mutate the strings as you don't call ToLower()
Only 2 lines of code
You can optionally precompile the expression if the expression (SOS|WAR) is a constant for more performance.
if (Regex.IsMatch(RI2.Text, "SOS|WAR", RegexOptions.IgnoreCase))
Response.Redirect("http://mydomain.com/rabat");

Not sure I fully understand your requirements, but here you go:
if(RI2.Text.ToLower().Contains("sos") || RI2.Text.ToLower().Contains("war")) {
Response.Redirect("http://mydomain.com/rabat");
}

you can do one call, like
//this will accept "SOS" and "sos"
if(RI2.Text.ToLower().Contains("sos") ||
RI2.Text.ToLower().Contains("war"))
{
....
}

You could convert the string to lowercase removing one if statement and then use a linq any statement.
var search=new[] {"sos","war"};
if (search.Any(x=>RI2.Text.ToLower().Contains(x))) {
Response.Redirect("http://mydomain.com/rabat");
}
Or even make collection of matches to target urls.
var search = new Dictionary<string,string>{
{"sos","http://mydomain.com/rabat"},
{"war","http://mydomain.com/rabat"},
};
The use linq
var url=search.Keys.Where(x=>RI2.Text.ToLower().Contains(x)).Select(x=>search[x]).FirstOrDefault();
if (url!=null) {
Response.Redirect(url);
}

You could create a extention to string as follows
public static bool Contains(this string value, string[] values)
{
foreach (string comparar in values)
{
if (value.ToUpper().Contains(comparar.ToUpper())) return true;
}
return false;
}

Instead of converting the string to lower or upper case use string.IndexOf with ignore case
if (RI2.Text.IndexOf("sos",StringComparison.InvariantCultureIgnoreCase) >= 0 ||
RI2.Text.IndexOf("war",StringComparison.InvariantCultureIgnoreCase) >= 0 )
{
Response.Redirect("http://mydomain.com/rabat");
}

if(string.Equals("war", RI2.Text, StringComparison.InvariantCultureIgnoreCase) ||
string.Equals("sos", RI2.Text, StringComparison.InvariantCultureIgnoreCase))
Response.Redirect("http://mydomain.com/rabat");

Create a list of string pairs, with one being the search string in upper case and the other being the redirect location.
Iterate through the list checking each search string against the upper-case text. If you find a match redirect to the location specified in the pair.

Use Regex:
var pattern = "(sos|war)";
if(Regex.IsMatch(RI2.Text.ToLower(), pattern))
Response.Redirect("http://mydomain.com/rabat");

Given that both the Url for Response.Redirect are same
string lowerRI2 = RI2.Text.ToLower();
if (lowerRI2.Contains("sos") || lowerRI2.Contains("war"))
Response.Redirect("http://mydomain.com/rabat");

Related

How to remove character from string?

I have a string which is getting from a userInput. What I want to do now is removing a unique character from this string but only remove it once. The main problem is that this unique character doesn't have a unique index. For example:
User has input a string like : "0123456", and now I want to remove the first '1',so the string will be output like "023456". How ever, if a user input a string like "01123456", how can I remove the first '1' and make it looks like "0123456"? I am looking for a method that can be used for both of situation. I was using string.TrimStart(), but doesn't get what I want. How can I do this?
You could use Remove and IndexOf.
var str = "01123456";
var i = str.IndexOf('1'); // IndexOf returns -1 when there is no element found, so we need to handle that when calling remove.
var res = (i >= 0) ? str.Remove(i, 1) : str;
Console.WriteLine(res); // 0123456
I think you what you need is string.Remove method. See MSDN documentation here: https://learn.microsoft.com/en-us/dotnet/api/system.string.remove?view=netframework-4.7.2#System_String_Remove_System_Int32_System_Int32_
If you don't know where is your character, at first call string.IndexOf to find it. If this call returns nonnegaive number, call Remove to remove it. Just note that string is immutable so it will always create a new object.
yourstring = yourstring.IndexOf('1') != -1 ? yourstring.Remove(yourstring.IndexOf('1'), 1) : yourstring;
Another way would be to use a combination of Contains, Remove, and IndexOf:
if (userInput.Contains('1')) userInput = userInput.Remove(userInput.IndexOf('1'), 1);
Or if you want to be Linq-y...
userInput = string.Concat(userInput.TakeWhile(chr => chr != '1')
.Concat(userInput.SkipWhile(chr => chr != '1').Skip(1)));

Regex for string without spacial characters or spaces [duplicate]

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-]+$

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

BestPractice - Transform first character of a string into lower case

I'd like to have a method that transforms the first character of a string into lower case.
My approaches:
1.
public static string ReplaceFirstCharacterToLowerVariant(string name)
{
return String.Format("{0}{1}", name.First().ToString().ToLowerInvariant(), name.Substring(1));
}
2.
public static IEnumerable<char> FirstLetterToLowerCase(string value)
{
var firstChar = (byte)value.First();
return string.Format("{0}{1}", (char)(firstChar + 32), value.Substring(1));
}
What would be your approach?
I would use simple concatenation:
Char.ToLowerInvariant(name[0]) + name.Substring(1)
The first solution is not optimized because string.Format is slow and you don't need it if you have a format that will never change. It also generates an extra string to covert the letter to lowercase, which is not needed.
The approach with "+ 32" is ugly / not maintainable as it requires knowledge of ASCII character value offsets. It will also generate incorrect output with Unicode data and ASCII symbol characters.
Depending on the situation, a little defensive programming might be desirable:
public static string FirstCharacterToLower(string str)
{
if (String.IsNullOrEmpty(str) || Char.IsLower(str, 0))
return str;
return Char.ToLowerInvariant(str[0]) + str.Substring(1);
}
The if statement also prevents a new string from being built if it's not going to be changed anyway. You might want to have the method fail on null input instead, and throw an ArgumentNullException.
As people have mentioned, using String.Format for this is overkill.
Just in case it helps anybody who happens to stumble across this answer.
I think this would be best as an extension method, then you can call it with yourString.FirstCharacterToLower();
public static class StringExtensions
{
public static string FirstCharacterToLower(this string str)
{
if (String.IsNullOrEmpty(str) || Char.IsLower(str, 0))
{
return str;
}
return Char.ToLowerInvariant(str[0]) + str.Substring(1);
}
}
The fastest solution I know without abusing c#:
public static string LowerCaseFirstLetter(string value)
{
if (value?.Length > 0)
{
var letters = value.ToCharArray();
letters[0] = char.ToLowerInvariant(letters[0]);
return new string(letters);
}
return value;
}
Mine is
if (!string.IsNullOrEmpty (val) && val.Length > 0)
{
return val[0].ToString().ToLowerInvariant() + val.Remove (0,1);
}
I like the accepted answer, but beside checking string.IsNullOrEmpty I would also check if Char.IsLower(name[1]) in case you are dealing with abbreviation. E.g. you would not want "AIDS" to become "aIDS".
If you care about performance I would go with
public static string FirstCharToLower(this string str)
=> string.Create(str.Length, str, (output, input) =>
{
input.CopyTo(output);
output[0] = char.ToLowerInvariant(input[0]);
});
I did some quick benchmarking and it seems to be at least twice as fast as the fastest solution posted here and 3.5 times faster than the worst one across multiple input lengths.
There is no input checking as it should be the responsibility of the caller. Allowing you to prepare your data in advance and do fast bulk processing not being slowed down by having branches in your hot path if you ever need it.
With range operator C# 8.0 or above you can do this:
Char.ToLowerInvariant(name[0]) + name[1..];
Combined a few and made it a chainable extension. Added short-circuit on whitespace and non-letter.
public static string FirstLower(this string input) =>
(!string.IsNullOrWhiteSpace(input) && input.Length > 0
&& char.IsLetter(input[0]) && !char.IsLower(input[0]))
? input[0].ToString().ToLowerInvariant() + input.Remove(0, 1) : input;
This is a little extension method using latest syntax and correct validations
public static class StringExtensions
{
public static string FirstCharToLower(this string input)
{
switch (input)
{
case null: throw new ArgumentNullException(nameof(input));
case "": throw new ArgumentException($"{nameof(input)} cannot be empty", nameof(input));
default: return input.First().ToString().ToLower() + input.Substring(1);
}
}
}
Use This:
string newName= name[0].ToString().ToLower() + name.Substring(1);
If you don't want to reference your string twice in your expression you could do this using System.Linq.
new string("Hello World".Select((c, i) => i == 0 ? char.ToLower(c) : c).ToArray())
That way if your string comes from a function, you don't have to store the result of that function.
new string(Console.ReadLine().Select((c, i) => i == 0 ? char.ToLower(c) : c).ToArray())
It is better to use String.Concat than String.Format if you know that format is not change data, and just concatenation is desired.

Problem Checking the End of a String

This seems to be a very odd problem that I cannot figure out for the life of me. I have a path (string) that looks like this:
D:\development\php\bchat\chat\index.php
I need to check if the file in question is a PHP file. I figure the most logical way is to take a substring starting from the . to the end of the string and see if it == .php
So i tried:
bool isphp = (path.Substring(path.LastIndexOf('.')) == ".php") ? true : false;
This always returned false. I thought maybe there was a trailing space at the end screwing me up so i put a TrimEnd() on path before it. But that didn't change anything. So i tried this:
bool isphp = (path.EndsWith(".php") == true) ? true : false;
This also always returns false.
EDIT
I have now also tried this:
bool isphp = (Path.GetExtension(path) == ".php");
But this also returns false.
Use the Path-class. It has a GetExtension() method:
var path = #"D:\development\php\bchat\chat\index.php";
if( Path.GetExtension( path.ToUpperInvariant() ) == ".PHP" )
{}
EDIT: Added check for upper/lower cases
The following code works fine on my machine:
public static void Main()
{
string path = #"D:\development\php\bchat\chat\index.php";
bool isPhp = path.EndsWith(".php");
Console.WriteLine(isPhp);
}
So I would guess there is something else about your string that is causing it not to work. Maybe it is a case thing in which case add StringComparison.InvariantCultureIgnoreCase to your EndsWith call like this.
public static void Main()
{
string path = #"D:\development\php\bchat\chat\index.pHp";
bool isPhp = path.EndsWith(".php", StringComparison.OrdinalIgnoreCase);
Console.WriteLine(isPhp);
}
If that doesn't work put a break point on the comparison line and then type this into the Immediate window:
path[path.Length-1]
You should get this as a result:
112 'p'
If you don't you can tell that your path does not end with a standard p character.
Just a sample for the posted solution:
bool isphp = Path.GetExtension(path)
.Equals(".php", StringComparison.InvariantCultureIgnoreCase);
If it is an existing file you can get the FileInfo object for it and check the extension that way:
FileInfo fi = new FileInfo(#"D:\development\php\bchat\chat\index.php");
if (fi.Exists && fi.Extension == ".php")
{
//Do something
}
Or I suppose you could be a sheep, follow the crowd and use the far better Path.GetExtension method that everyone else has suggested. But ask yourself this question first - do you want to do it the cleanest, fastest and best way, or do you want to assert your individuality and join me down the path of most resistance?
Use Path.GetExtension and compare with the file type you're looking for.
What about Path.GetExtension method?
Make sure that there is no difference in upper/lowercase. You are only testing for lowercase "php".
string ext = Path.GetExtension(path);
bool isPhp = (ext.Equals(".php", StringComparison.InvariantCultureIgnoreCase));
UPDATE:
Check what path.Substring(path.LastIndexOf('.') actually returns - that might point you in the right direction.
private static bool IsPhp(string fileName)
{
return string.Compare(Path.GetExtension(fileName), ".php",
StringComparison.OrdinalIgnoreCase) == 0;
}
I suspect there's something "odd" in your string. I suggest you dump your string out in detail, like this:
foreach (char c in path)
{
Console.WriteLine("'{0}' U+{1:x4}", c, (int) c);
}
That way you'll see any unexpected characters, e.g. unicode char 0s between "real" characters.

Categories