Length of a string in c# WinForm - c#

I have a text box in my form and I want to check if the first char is equal to something,
basically I want it to do this :
if(Textbox1.text.length(0) == "a")
{
do stuff
}

Eh, are you looking for
if (Textbox1.Text.StartsWith("a")) {
// do stuff
...
}

.length only returns an integer of length of the string.
This will compare the first char with 'a'.
if(Textbox1.text[0] == 'a')

you can do this by two ways...
one i mentioned in your question's comment
second is
if(myTextBox.Text[0] == 'B')
{
//do studd
}

try smething like this:
Textbox1.Text.StartsWith("a") ? do something : do something else;
and if it is not just about first character then try something like:
Textbox1.Text.Contains("a") ? do something : do something else;

if(textBox1.Text.Substring(0,1)=="a")

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

Check What Letters are in a String

I am making a Hangman Game in C# in WPF, and I am wondering if there is a way to check what letters are in a string so that if a letter is choosen the program can determine if the letter is in the chosen word or not.
Ex.
String StackOverFlow; //Sample String
//If Letter "A" is chosen,
private void AButt_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
//What Would I Put Here?
}
You could use Contains(), but that is going to be case sensitive. Hangman is not.
The easiest way to handle that is to use IndexOf() instead:
if(StackOverFlow.IndexOf("A", StringComparison.CurrentCultureIgnoreCase) > -1)
{
// Found
}
else
{
// Not Found
}
You could use the String.Contais method. And don't create one event handler for each letter - create only one which checks what letter was input, then do something according to it existing in the string or not.
Use Contains:
StackOverFlow.Contains("A");
If you also want to know where in the word the letter first appears, you can use IndexOf:
StackOverFlow = "EXAMPLE"
StackOverFlow.IndexOf("A"); //returns 2
StackOverFlow.IndexOf("B"); //returns -1 because it is not present
You can use ToLower() first to tackle case-sensitivity:
StackOverflow.ToLower().Contains("a")

how to check if the character is an integer

I am looking for a function that can check the character if it is a integer and do something is so.
char a = '1';
if (Function(a))
{
do something
}
Use System.Char.IsDigit method
If you want just the pure 0-9 digits, use
if(a>='0' && a<='9')
IsNumeric and IsDigit both return true for some characters outside the 0-9 range:
Difference between Char.IsDigit() and Char.IsNumber() in C#
Integer.TryParse works well.
http://msdn.microsoft.com/en-us/library/f02979c7.aspx
The bool Char.IsDigit(char c); Method should work perfectly for this instance.
char a = '1';
if (Char.IsDigit(a))
{
//do something
}
Try using System.Char.IsDigit method.
Try Char.IsNumber. Documentation and examples can be found here
It may be better to just use a switch statement. Something like:
switch(a)
{
case '1':
//do something.
break;
case '2':
// do something else.
break;
default: // Not an integer
throw new FormatException();
break;
}
This will work as long as you're only looking for characters 0-9. Anything more than that (say "10") would be a string and not a character. If you're trying to just see if some input is an integer and the input is a string, you can do:
try
{
Convert.ToInt32("10")
}
catch (FormatException err)
{
// Not an integer, display some error.
}
I have to check the first to characters of a string and if the third character is numeric and do it with MyString.All(char.IsDigit):
if (cAdresse.Trim().ToUpper().Substring(0, 2) == "FZ" & cAdresse.Trim().ToUpper().Substring(2, 1).All(char.IsDigit))
Simplest answer:
char chr = '1';
char.isDigit(chr)

If else minifier

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

How to check the first two values of a string

I would like to check the input value of a telephone number (to check if it starts with 06 or 07) and accordingly make changes in a query.
How to go about this?
Will the following work:
char first = strNewTel.Trim()[0];
char sec = strNewTel.Trim()[1];
...and then check the two chars if they match.
Or is there an better way to do this? Thanks!
if (!string.IsNullOrEmpty(strNewTel)
&& (strNewTel.StartsWith("06")
|| strNewTel.StartsWith("07")) {
}
Simple as that:
if (strNewTel.Trim().StartsWith("06") || strNewTel.Trim().StartsWith("07"))
{
// DoSomething
}
String phone = "067-123-4567";
if (phone.StartsWith("06")) {
//add logic here
}
Good luck!
strNewTel.StartsWith("06")||strNewTel.StartsWith("07")
Why not StartsWith that should do the job
If I got you right and you mean "check if number starts from 06 or 07" then use
strNewTel.Trim().StartsWith("06")

Categories