validate variable contains string value - c#

I have one variable which contains string value like below:
var stringWithSpecialChar = "/Home%";
Sometimes this variable does not contain any value like below:
var stringWithSpecialChar = "/%";
I have to check here whether this variable contains string value or not.
Everytime string value is changing so it is not sure that i will get the same value another time.

I can't understand what is a valid value in your question, so:
Use below code if a valid value is a value of some letters or some digits:
using System.Linq;
if (str.Any(char.IsLetterOrDigit)
{
//Some codes
}
But I recommend you; for checking a valid or invalid string use Regex like this:
using System.Text.RegularExpressions;
var regex = new Regex(#"[A-Za-z]"); // You have many options here
if (regex.IsMatch(str))
{
//Some codes
}

You can do this, do a foreach loop on your variable to check if it will see a string or letter.
var stringWithSpecialChar = "/Home%";
bool blStringInput;
blStringInput = IsThisString(stringWithSpecialChar);
Method to check if it will see a string value:
public static bool IsThisString(string strInput)
{
foreach (char c in strInput)
{
if (char.IsLetter(c))
return true;
}
return false;
}

Below is a simple implementation of your problem. I have considered that anything in between / and % is a string [It might contain numbers, alphabets or special characters]. Also, I have included a check inside the function whether the string is valid or not by checking whether it starts and ends with / and % respectively.
using System;
class MainClass {
public static void Main (string[] args) {
var stringWithSpecialChar = "/Home%";
bool ans = checkIfStringIsPresent(stringWithSpecialChar);
Console.WriteLine(ans);
stringWithSpecialChar = "/%";
ans = checkIfStringIsPresent(stringWithSpecialChar);
Console.WriteLine(ans);
stringWithSpecialChar = "/hi%";
ans = checkIfStringIsPresent(stringWithSpecialChar);
Console.WriteLine(ans);
stringWithSpecialChar = "/12#%";
ans = checkIfStringIsPresent(stringWithSpecialChar);
Console.WriteLine(ans);
}
public static bool checkIfStringIsPresent(string s){
var len = s.Length;
if(s[0]!='/' || s[len-1]!='%')
return false; // if string doesn't start and and with correct symbols, then return false
var i = 0;
for(i=1;i<len-1;i++){
return true; // something is present in between / and %, so return true
}
return false; // else return false
}
}
Output:
True
False
True
True

If you know the special characters and know they are at the begining and end of the string, Trim() could be used:
var stringWithSpecialChar = "/Home%";
var value = stringWithSpecialChar.Trim('/', '%');
if(!string.IsNullOrEmpty(value))
// Use value...
One could also use string.IsNullOrWhiteSpace(value) in the condition depending on your needs.

Related

How to add numbers in a mixed string C#

example = "I-000146.22.43.24"
In the example, I need to validate that the last number after the period isnt over 9. Currently is 24 and thats not valid.
01-08 is valid and anything over that isnt.
How can I add logic to check for this?
One solution would be to use Regex. The regex pattern would be something like this:
^.+\.(0?[0-8])$
Regex demo.
C# example:
string pattern = #"^.+\.(0?[0-8])$";
string[] inputs = new [] { "I-000146.22.43.24", "I-000146.22.43.09",
"I-000146.22.43.08", "xxxxxxx.07" };
foreach (string input in inputs)
{
Match match = Regex.Match(input, pattern);
if (match.Success)
Console.WriteLine($"The input is valid. Last number is '{match.Groups[1].Value}'.");
else
Console.WriteLine("The input is not valid.");
}
Output:
The input is not valid.
The input is not valid.
The input is valid. Last number is '08'.
The input is valid. Last number is '07'.
Try it online.
You could use Linq:
using System;
using System.Linq;
class MainClass {
public static void Main (string[] args) {
String[] tests = new string[3] {"I-000146.22.43.24", "I-000146.22.43.9", "I-000146.22.43.a"};
foreach (string test in tests) {
Console.WriteLine ($"{test} is a valid string: {isValidString (test)}");
}
}
private static bool isValidString (string str) {
var lastNumString = str.Split ('.').Last();
return isSingleDigit (lastNumString);
}
private static bool isSingleDigit (string numString) {
int number;
bool success = Int32.TryParse (numString, out number);
if (success) {
return number >= 0 && number <= 9;
}
return success;
}
}
Output:
I-000146.22.43.24 is a valid string: False
I-000146.22.43.9 is a valid string: True
I-000146.22.43.a is a valid string: False

how to refactor code to return IsPalindrome

using a mock c# question on https://www.testdome.com/t
I have coded
using System;
public class Palindrome
{
public static bool IsPalindrome(string word)
{
string testWord = word;
string first = word[0].ToString();
string last = word[word.Length - 1].ToString();
bool isPal = false;
while (testWord.Length > 1)
{
Console.WriteLine(testWord);
if (first.ToLower() == last.ToLower())
{
testWord = testWord.Remove(0,1);
testWord = testWord.Remove(testWord.Length - 1);
isPal = true;
}
}
return isPal;
}
public static void Main(string[] args)
{
Console.WriteLine(Palindrome.IsPalindrome("Deleveled"));
}
}
this code is working but it is failing me on
lowercase words: time limit exceeded
various words: time limit exceeded.
What changes could I make to refactor the code to work faster?
No need to write multiple line of code, you can check Palindrome in one line,
Magic of Linq,
bool isPalindrome = str.SequenceEqual(str.Reverse());
If you want to ignore case then convert original string and reverse string to lower case and then check its sequence
string str = "Madam";
var strReverse = str.ToLower().Reverse();
var isPalindrome = str.ToLower().SequenceEqual(strReverse);
Basically, Palindrome check is a check where actual string is equal to its reverse. When we check original string to reverse string that time we need not to travel till the end. We just need to check first letter with it's last and so on...
Here is non-Linq Palindrome check,
public static bool IsPalindrome(string word)
{
string testWord = word;
for(int i = 0; i < word.Length/2; i++)
{
if(char.ToLower(testWord[i]) != char.ToLower(testWord[testWord.Length - i - 1]))
return false;
}
return true;
}
POC : . net fiddle
One thing you can do is immediately return if you find a non-match.

Parsing to double and ignoring letters and whitespace

I define the prices here:
lblPrisGrill.Text = "20,00 ,-"; // Grill
lblPrisWiener.Text = "25,00 ,-"; // Wiener
lblPrisBacon.Text = "35,00 ,-"; // Bacon
lblPrisOst.Text = "30,00 ,-"; // Oste
I parse the price from string to double (number):
if (rbGrill.Checked == true)
PrisMeny = double.Parse(lblPrisGrill.Text);
else if (rbWiener.Checked == true)
PrisMeny = double.Parse(lblPrisWiener.Text);
else if (rbBacon.Checked == true)
PrisMeny = double.Parse(lblPrisBacon.Text);
else if (rbOst.Checked == true)
PrisMeny = double.Parse(lblPrisOst.Text);
I would like to know how I could only get the number "##,##" and ignore the " ,-".
I know there exists resources explaining this, but I would like to know how this would be if I have multiple tasks and see how it would be done.
You can simply use String.Replace to remove that part:
string s = "20,00 ,-";
double d = double.Parse(s.Replace(",-", ""));
Console.WriteLine(d); // 20.0
You can use Regex to find the matched expression. I have created this dotnet fiddle to demonstrate your scenario. You can check the output in fiddle. Attaching the code for reference.
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
var text = "200,001 ,-";
var regex = new Regex(#"\d\d*,\d\d*");
foreach(var match in regex.Matches(text))
{
Console.WriteLine(match.ToString());
}
}
}

C# how can I check users input

I´m having a string with allowed chars. I´d like that user is only able to use this chars.
My idea was to loop through the unser inputs string and compare char for char. But the problem which I have is when the first char in string allowed is "A" and the first in the users input "B" is, it gives me an error...
Totally confused right now
string allowed = "abc";
string read= Console.ReadLine();
for (int i = 0; i < allowed.Length; i++ )
{
if (allowed[i] == read[i])
{
Console.WriteLine("Okay");
}
else
{
Console.WriteLine("Invalid char on" +index);
}
}
If you wanna check if the user input has any of not allowed characters you need a nested loop, because you wanna compare each char in the user input against the chars in the allowed:
foreach(var r in read)
{
bool isValid = false;
foreach(var c in allowed)
{
// if we found a valid char set isValid to true
if(c == r)
isValid = true;
}
// if it's still false then the current char
// doesn't match any of the allowed chars
// so it's invalid
if(!isValid)
{
Console.WriteLine("the string has invalid char(s)");
break;
}
}
Or, to simplify this you can use LINQ:
bool isInvalid = read.Any(c => !allowed.Contains(c));
If you want to know which chars are invalid, you can use Except method:
var invalidChars = read.Except(allowed);
foreach(var c in invalidChars)
{
Console.WriteLine(c);
}
You either need to search the char of user input within the allowed characters or you could use a regular expression.
Search approach:
private string allowed = "abc";
private string userInput = "some string entered";
bool stringIsValid = false;
for (int i = 0; i < userInput.Length; i++)
{
if (!allowed.IndexOf(userInput[i]))
{
stringIsValid = false;
break; // You can stop the loop upon the first occurance of an invalid char
}
}
Regular expression approach:
private string allowed = "abc";
private string userInput = "some string entered";
bool stringIsValid = Regex.IsMatch(allowed, userInput);
Please note that the regular expression approach is more flexible. If you learn about regular expressions, you will find it very powerful.
You need another loop in your first one:
string allowed = "abc";
string read= Console.ReadLine();
for (int i = 0; i < read.Length; i++ )
{
bool isValid = false;
for (int j = 0; j < allowed.Length; j++)
{
if (read[i] == allowed[j])
{
isValid = true;
break;
}
}
if (isValid)
{
Console.WriteLine("Okay");
}else{
Console.WriteLine("Invalid char on" +index);
}
}
Right now, what you're saying is "every character in read must be exactly the same as in allowed".
What you're trying to say (I think) is "every character in read must be present somewhere in allowed" – that's what the second loop does. It looks for the character in allowed and if it finds it, sets isValid to true. Otherwise the character wasn't found and it's incorrect.
As other answers here state, you can use LINQ or (preferrably) regular expressions (regex) for things like this. I assume this is homework, or you're new to C# or programming, so I provided a basic answer to (hopefully) help you understand what's not working currently with your code.
If this should indeed be a homerwok or studying-related question, then let me recommend you put that in your question next time, for it's not forbidden to ask about homework.
The "real world" solutions we would use are of no help to you if you're trying to figure out the basics, so if we know it's about learning stuff then we'll provide answers that are more useful for you.
When using a collection to store not allowed items (instead of a plain string) it opens a whole new spectrum of LINQ expressions you can use:
public static void Main(string[] args)
{
var allowed = new List<string> { "a", "b", "c" };
var read = Console.ReadLine().Select(c => c.ToString()).ToList();
if (read.All(allowed.Contains))
{
Console.WriteLine("Okay");
}
else
{
var firstNotAllowed = read.First(a => !allowed.Contains(a));
var firstIndex = read.FindIndex(a => !allowed.Contains(a));
Console.WriteLine("Invalid char: {0}, at index: {1}", firstNotAllowed, firstIndex);
}
}

How can I check if a string is a number?

I'd like to know on C# how to check if a string is a number (and just a number).
Example :
141241 Yes
232a23 No
12412a No
and so on...
Is there a specific function?
Look up double.TryParse() if you're talking about numbers like 1, -2 and 3.14159. Some others are suggesting int.TryParse(), but that will fail on decimals.
string candidate = "3.14159";
if (double.TryParse(candidate, out var parsedNumber))
{
// parsedNumber is a valid number!
}
EDIT: As Lukasz points out below, we should be mindful of the thread culture when parsing numbers with a decimal separator, i.e. do this to be safe:
double.TryParse(candidate, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var parsedNumber)
If you just want to check if a string is all digits (without being within a particular number range) you can use:
string test = "123";
bool allDigits = test.All(char.IsDigit);
Yes there is
int temp;
int.TryParse("141241", out temp) = true
int.TryParse("232a23", out temp) = false
int.TryParse("12412a", out temp) = false
Hope this helps.
Use Int32.TryParse()
int num;
bool isNum = Int32.TryParse("[string to test]", out num);
if (isNum)
{
//Is a Number
}
else
{
//Not a number
}
MSDN Reference
Use int.TryParse():
string input = "141241";
int ouput;
bool result = int.TryParse(input, out output);
result will be true if it was.
Yep - you can use the Visual Basic one in C#.It's all .NET; the VB functions IsNumeric, IsDate, etc are actually static methods of the Information class. So here's your code:
using Microsoft.VisualBasic;
...
Information.IsNumeric( object );
int value;
if (int.TryParse("your string", out value))
{
Console.WriteLine(value);
}
This is my personal favorite
private static bool IsItOnlyNumbers(string searchString)
{
return !String.IsNullOrEmpty(searchString) && searchString.All(char.IsDigit);
}
Perhaps you're looking for the int.TryParse function.
http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx
Many datatypes have a TryParse-method that will return true if it managed to successfully convert to that specific type, with the parsed value as an out-parameter.
In your case these might be of interest:
http://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx
http://msdn.microsoft.com/en-us/library/system.decimal.tryparse.aspx
int result = 0;
bool isValidInt = int.TryParse("1234", out result);
//isValidInt should be true
//result is the integer 1234
Of course, you can check against other number types, like decimal or double.
You should use the TryParse method for the int
string text1 = "x";
int num1;
bool res = int.TryParse(text1, out num1);
if (res == false)
{
// String is not a number.
}
If you want to validate if each character is a digit and also return the character that is not a digit as part of the error message validation, then you can loop through each char.
string num = "123x";
foreach (char c in num.ToArray())
{
if (!Char.IsDigit(c))
{
Console.WriteLine("character " + c + " is not a number");
return;
}
}
int.TryPasrse() Methode is the best way
so if the value was string you will never have an exception , instead of the TryParse Methode return to you bool value so you will know if the parse operation succeeded or failed
string yourText = "2";
int num;
bool res = int.TryParse(yourText, out num);
if (res == true)
{
// the operation succeeded and you got the number in num parameter
}
else
{
// the operation failed
}
string str = "123";
int i = Int.Parse(str);
If str is a valid integer string then it will be converted to integer and stored in i other wise Exception occur.
Starting with C# 7.0, you can declare the out variable in the argument
list of the method call, rather than in a separate variable
declaration. This produces more compact, readable code, and also
prevents you from inadvertently assigning a value to the variable
before the method call.
bool isDouble = double.TryParse(yourString, out double result);
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier
You could use something like the following code:
string numbers = "numbers you want to check";
Regex regex = new Regex("^[0-9]+$"));
if (regex.IsMatch(numbers))
{
//string value is a number
}
public static void Main()
{
string id = "141241";
string id1 = "232a23";
string id2 = "12412a";
validation( id, id1, id2);
}
public static void validation(params object[] list)
{
string s = "";
int result;
string _Msg = "";
for (int i = 0; i < list.Length; i++)
{
s = (list[i].ToString());
if (string.IsNullOrEmpty(s))
{
_Msg = "Please Enter the value";
}
if (int.TryParse(s, out result))
{
_Msg = "Enter " + s.ToString() + ", value is Integer";
}
else
{
_Msg = "This is not Integer value ";
}
}
}
Try This
here i perform addition of no and concatenation of string
private void button1_Click(object sender, EventArgs e)
{
bool chk,chk1;
int chkq;
chk = int.TryParse(textBox1.Text, out chkq);
chk1 = int.TryParse(textBox2.Text, out chkq);
if (chk1 && chk)
{
double a = Convert.ToDouble(textBox1.Text);
double b = Convert.ToDouble(textBox2.Text);
double c = a + b;
textBox3.Text = Convert.ToString(c);
}
else
{
string f, d,s;
f = textBox1.Text;
d = textBox2.Text;
s = f + d;
textBox3.Text = s;
}
}
I'm not a programmer of particularly high skills, but when I needed to solve this, I chose what is probably a very non-elegant solution, but it suits my needs.
private bool IsValidNumber(string _checkString, string _checkType)
{
float _checkF;
int _checkI;
bool _result = false;
switch (_checkType)
{
case "int":
_result = int.TryParse(_checkString, out _checkI);
break;
case "float":
_result = Single.TryParse(_checkString, out _checkF);
break;
}
return _result;
}
I simply call this with something like:
if (IsValidNumber("1.2", "float")) etc...
It means that I can get a simple true/false answer back during If... Then comparisons, and that was the important factor for me. If I need to check for other types, then I add a variable, and a case statement as required.
use this
double num;
string candidate = "1";
if (double.TryParse(candidate, out num))
{
// It's a number!
}
int num;
bool isNumeric = int.TryParse("123", out num);
namespace Exception
{
class Program
{
static void Main(string[] args)
{
bool isNumeric;
int n;
do
{
Console.Write("Enter a number:");
isNumeric = int.TryParse(Console.ReadLine(), out n);
} while (isNumeric == false);
Console.WriteLine("Thanks for entering number" + n);
Console.Read();
}
}
}
Regex.IsMatch(stringToBeChecked, #"^\d+$")
Regex.IsMatch("141241", #"^\d+$") // True
Regex.IsMatch("232a23", #"^\d+$") // False
Regex.IsMatch("12412a", #"^\d+$") // False
The problem with some of the suggested solutions is that they don't take into account various float number formats. The following function does it:
public bool IsNumber(String value)
{
double d;
if (string.IsNullOrWhiteSpace(value))
return false;
else
return double.TryParse(value.Trim(), System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out d);
}
It assumes that the various float number styles such es decimal point (English) and decima comma (German) are all allowed. If that is not the case, change the number styles paramater. Note that Any does not include hex mumbers, because the type double does not support it.

Categories

Resources