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")
Related
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")
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")
I'm trying to validate a textbox to check that it has a phone number type value entered.
The problem I'm having is that even when the entry is for example: "blah" in these text boxes the Regex is still returning false and no error message is shown.
Regex staffNumVal = new Regex(#"^[a-z]+$");
if (staffNumVal.IsMatch(txtStaffHPhone.Text)||(staffNumVal.IsMatch(txtStaffHourRate.Text)))
{
MessageBox.Show("Please enter a numeric value");
}
Is there a better way to do this that I'm missing? Thanks.
Instead of
Regex staffNumVal = new Regex(#"^[a-z]+$");
Use
Regex staffNumVal = new Regex(#"^[0-9]+$");
if (staffNumVal.IsMatch(txtStaffHPhone.Text)||(staffNumVal.IsMatch(txtStaffHourRate.Text)))
{
//Valid
}
else
{
MessageBox.Show("Please enter a numeric value");
}
Regex staffNumVal = new Regex(#"^\d*$");
Try it like so
int value;
if (int.TryParse(txtStaffHPhone.Text, out value))
{
// it's a valid integer
}
Regex regex = new Regex(#"^\d$");
Refer for Details: Regex for numbers only
Your RegEx does not do what you expect it.
I think the '^' is misplaced. It should be: #"[^a-z]+$".
But even that is wrong, since it accepts things like &.
You can test at: http://regexhero.net/tester/
But I think you'll be better served with a MaskedTestBox. Have you tried that?
Import Microsoft.VisualBasic and use it!
if (Microsoft.VisualBasic.Information.IsNumeric("5"))
{
//Do Something
}
Instead of doing this, I want to make use of string.format() to accomplish the same result:
if (myString.Length < 3)
{
myString = "00" + 3;
}
If you're just formatting a number, you can just provide the proper custom numeric format to make it a 3 digit string directly:
myString = 3.ToString("000");
Or, alternatively, use the standard D format string:
myString = 3.ToString("D3");
string.Format("{0:000}", myString);
It's called Padding:
myString.PadLeft(3, '0')
This is how it's done using string interpolation C# 7
$"{myString:000}"
(Can't comment yet with enough reputation , let me add a sidenote)
Just in case your output need to be fixed length of 3-digit , i.e. for number run up to 1000 or more (reserved fixed length), don't forget to add mod 1000 on it .
yourNumber=1001;
yourString= yourNumber.ToString("D3"); // "1001"
yourString= (yourNumber%1000).ToString("D3"); // "001" truncated to 3-digit as expected
Trail sample on Fiddler https://dotnetfiddle.net/qLrePt
This is a short hand string format Interpolation:
$"{value:D3}"
"How to: Pad a Number with Leading Zeros"
http://msdn.microsoft.com/en-us/library/dd260048.aspx
Does it have to be String.Format?
This looks like a job for String.Padleft
myString=myString.PadLeft(3, '0');
Or, if you are converting direct from an int:
myInt.toString("D3");
You can also do : string.Format("{0:D3}, 3);
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");