Not getting third character from right from the string in c# - c#

Here if my usename is Rus7AE then i want to take the number value i.e. third character from right. t.e. 7. Following code is not returning me the value 7 ?
studentA consists of 5-7th std studentB consists of 8-10th std studentC consists of 5-10th std thats common group but doesnt contains same values from studentA and studentB
private void authcheck()
{
username = Session["stud"].ToString();
schlName = Session["stuschname"].ToString();
string value = username.ToString();
int groupName = Convert.ToInt32(value[value.Length - 3]);
Session["grpName"] = groupName.ToString();
}
How can i get the thirdlast value

You are trying to convert a character to a numeric value, which will not give the intended result.
Try
int groupName = int.Parse(value.Substring(value.Length - 3, 1));
If it is possible that you will receive data not in this format, look at int.TryParse instead.
Convert.ToInt32 is not working because it takes the actual value of the character based on the current encoding and converts that to a character. For example,
int val = Convert.ToInt32('7');
Yields 55, which is the ASCII or UTF-8 code for '7'.

You don't get third last value because the conditions are wrong
if
5-7
else if
8-10
else if
5-10
Last one will never be hit in this case

since you can have "10" in your group-number (as i've seen in your code) and maybe some dual-digits more (11,12,13 etc.) we should use Regular Expressions here...
var regex = new Regex(#"\w+(\d+)\w+");
int groupNumber;
var match = regex.Match(subjectString);
if(!match.Success || !match.Groups[1].Success || !int.TryParse(match.Groups[1].Value, out groupNumber))
throw new Exception("Student has no group!?!?");
string groupName = null;
switch(groupNumber){
case 5:
case 6:
case 7:
groupName = "studentA";
break;
case 8:
case 9:
case 10:
groupName = "studentB";
break;
case 1:
case 2:
case 3:
case 4:
groupName = "studentC";
break;
default:
throw new Exception("invalid group number");
}

Related

if string value is used in case then we not need to convert there format before comparison?

I have used below code in a project and someone ask me to use ToLower() or ToUpper() and I think it is unnecessary.
public somefun(Classabc clsabc, string emptype, string id)
{
switch(emptype)
{
case :"AnyInput":
{
//do
}
break;
case :"StringInput":
{
//do
}
break;
}
}
if(emptype=="AnyInput")
{
///
}
Is the above perfect or we need to use ToLower() or ToUpper() with empType in if()? Is there any issue or programming rule violation with my code? According to me in case (switch) we are using email type as constant for case matching and if emptype value can be used in case matching then there is no need to add extra functions to convert to there case before string matching.
Depends on what you guys are looking for.
If the comparison is case sensitive, you can keep the switch-case comparison like you did in the example you provided.
In case the comparison is insensitive, you can pattern matching (C# 7 and above) and write something like this:
switch (true)
{
case bool b when emptype.Equals("AnyInput", StringComparison.InvariantCultureIgnoreCase):
// do
break;
case bool b when emptype.Equals("StringInput", StringComparison.InvariantCultureIgnoreCase):
// do
break;
default:
break;
}

Using enum as a variable (?) [duplicate]

This question already has answers here:
Convert a string to an enum in C#
(29 answers)
Closed 3 years ago.
I have a problem about some simple code in console. Precisely I created a public enum called Year which contains 4 seasons (obvious). I want the program to ask at the beginning what is the season of the year and then generate an answer to each option. The problem is I don't know how to convert my string input to each option of this enum. Maybe it will be more clear if i show you the code (it's short).
Console.WriteLine("What time of year is it?");
var input = Console.ReadLine();
//earlier it was just
//time = Year.Winter;
switch (time)
{
case Year.Autumn:
Console.WriteLine("You're gonna have to grab the leaves");
break;
case Year.Summer:
Console.WriteLine("Let's go to the beach");
break;
case Year.Winter:
Console.WriteLine("Better to warm up at home");
break;
case Year.Spring:
Console.WriteLine("Best time of the year!");
break;
default:
Console.WriteLine("I don't know this time of year");
break;
}
I want to make something like this but dunno what to put inside this switch statement because I can't just put there my string 'input'. Is it possible in the way I am thinking of it?
You can parse a try to parse a string into an Enum by using one of the Enum class.
In particular, you can use the typed method TryParse in this eay
var ignoreCase = true; // decide this
if (Enum.TryParse<MyEnum>("my string", ignoreCase, out var r))
// use r
else
Console.WriteLine("Please enter the correct value.");
You can use string contain() function before the switch statment like below i haven't tested if it works like this (nested) if not you have to use if and else if condition
time = input.Trim().Contains("winter") ? Year.Winter: (input.Trim().Contains("summer") ?Year.Summer :(input.Trim().Contains("autumn") ?Year.Autumn:i(nput.Trim().Contains("autumn") ?Year.Autumn: null)));
The other thing you can do is give user option like 1 Year.Autumn,2 Year.Summer,3 Year.Winter,4 Year.Spring and get a number on which you can use the switch statment

Is it possible to parse "-1.#IND", etc using Double.Parse method

Trying to use System.Double.Parse(string) method for strings such as "-1.#IND" and "INF" representing special values results in a FormatException.
Is there any built-in .NET framework support to parse these?
No, the only non-numeric values double.Parse recognizes are the string values returned by double.Nan.ToString(), double.PositiveInfinity.ToString(), and double.NegativeInfinity.ToString() (dependent on Culture).
In your case I would just use a switch:
double dblValue;
switch strValue
{
case "-1.#IND":
dblValue = double.Nan;
break;
case "INF":
dblValue = double.Infinity;
break;
//... other casess
default:
dblValue = double.Parse(strValue);
break;
}
NaN and other values are parsed in the specified culture (or neutral, if no culture is specified). You can play with those here if you want.
If you have to parse something more special, then just
public double MyParse(string text)
{
if(text == "blablabla")
return double.NaN;
if(text.Contains("blablabla")) ...
if(text.StartsWith(...
return double.Parse(text);
}

Char tryParse not working as I thought?

I have some problem with a method that I have done in c#. I'm trying to stop user from entering anything else then y and n. It's almost working that I want, but user can still enter more than one sign, and then it doesn't work! How can I do to also check if char is more than one char? I thought the tryParse solved that? Thanks!
// Method to check if item is food or not
private void ReadIfFoodItem()
{
Console.Write("Enter if food item or not (y/n): ");
if (char.TryParse(Console.ReadLine(), out responseFoodItem))
{
if(Char.IsNumber(responseFoodItem))
{
Console.WriteLine(errorMessage);
ReadIfFoodItem();
}
else
{
// Set true or false to variable depending on the response
if ((responseFoodItem == 'y' || responseFoodItem == 'Y'))
{
foodItem = true;
selectedVATRate = 12; // Extra variable to store type of VAT
}
else if ((responseFoodItem == 'n' || responseFoodItem == 'N'))
{
foodItem = false;
selectedVATRate = 25; // Extra variable to store type of VAT
}
else
{
Console.WriteLine(errorMessage);
ReadIfFoodItem();
}
}
}
}
The following code "works" in that it produces the expected results.
char responseFoodItem;
Console.Write("Enter if food item or not (y/n): ");
if (char.TryParse(Console.ReadLine(), out responseFoodItem))
{
// Set true or false to variable depending on the response
if ((responseFoodItem == 'y' || responseFoodItem == 'Y'))
{
Console.WriteLine("foodItem = true");
}
else if ((responseFoodItem == 'n' || responseFoodItem == 'N'))
{
Console.WriteLine("foodItem = false");
}
else
{
Console.WriteLine("Unrecognised input");
}
}
else
{
Console.WriteLine("Invalid input");
}
However, has others have pointed out using ReadKey is a better solution if you want to limit the input to a single key. It also means that the user doesn't have to press the Return/Enter key for the input to be accepted.
char represents a single character, so How can I do to also check if char is more than one char? I thought the tryParse solved that? seems a bit nonsensical... TryParse will try and parse a single character from your input and will explicitly fail if the value is null or has a length > 1.
Instead of checking a character, just check the string, e.g.:
string line = Console.ReadLine();
switch (line.ToUpperInvariant())
{
case "Y":
// Do work for y/Y
break;
case "N":
// Do work for n/N
break;
default:
// Show error.
break;
}
char.TryParse simply tries to parse the string supplied as an argument, it does not limit the number of characters that you can input to the console using Console.ReadLine.
When the user inputs more than a single character, char.TryParse will fail because the string returned by Console.ReadLine doesn't contain a single character.
You should use Console.Read instead.
How can I do to also check if char is more than one char?
string line = Console.ReadLIne();
If(!string.IsNullOrEmpty(line) && line.Length > 1)
for reading a single char use Console.ReadChar() instead.
Console.ReadLine allows users to type a string of any length and press enter.
How can I do to also check if char is more than one char? I thought the tryParse solved that?
From the manual page:
Converts the value of the specified string to its equivalent Unicode character. A return code indicates whether the conversion succeeded or failed....The conversion fails if the s parameter is null or the length of s is not 1.
Have you tried using Console.ReadKey instead of ReadLine?
To check it the user has inserted more then one char you could check the string length instead of use Char.TryParse
......
private void ReadIfFoodItem()
{
string answer=string.empty;
Console.Write("Enter if food item or not (y/n): ");
answer=Console.ReadLine()
if (answer.lenght>=1))
{
//error
.......
}
...............
This answer should help you: How can I limit the number of characters for a console input? C#
The console does not limit the user input (well it does, but to 256 characters), nor does char.TryParse which doesn't do anything at all to limit the input length.
You can try using Console.ReadKey
It's just one keystroke for the user and you know there won't be more than one char.
Why not comparing to the input'ed string?
And why not simplifying the comparison?
using System.Linq;
private static string[] ValidAnswers = new string[]{ "y", "yes" };
// Method to check if item is food or not
private void ReadIfFoodItem() {
Console.Write("Enter if food item or not (y/n): ");
string ans = Console.ReadLine();
// Checks if the answer matches any of the valid ones, ignoring case.
if (PositiveAnswers.Any(a => string.Compare(a, ans, true) == 0)) {
foodItem = true;
selectedVATRate = 12; // Extra variable to store type of VAT
} else {
foodItem = false;
selectedVATRate = 25; // Extra variable to store type of VAT
}
}
Alternatively, as others said, you can use Console.ReadKey().
Use Console.ReadKey() to limit the amount of characters. To test whether you have a Y or an N then you can compare the ASCII codes or use a regular expression.

String Comparison

Scenario
Consider the following code snippet.
string s = "S";
string s1 = "S";
string s2 = string.Empty;
switch (s)
{
case "S":
s1 = "StringComparison";
break;
default:
break;
}
switch (s[0])
{
case'S':
s2 = "StringCOmpare2";
break;
default:
break;
}
the first switch case, results in a stringcomparison within IL.
But the second switch case, does not result in a stringcomparison within IL.
Can anyone justify this?
Because on the second switch you're are not doing a String comparison, you're doing a Char comparison.
The easiest answer is that you're not doing a string comparison in the second block; you're comparing two characters.
However, you're right in that the two code blocks are functionally equivalent. A good optimizing compiler should be able to detect that 's' is a fixed-length string, and rewrite it not to use a full string comparison.
You're accessing the string via its indexer which returns a char and so lets you use the string as if it was an array of chars.
So whar you're doing is a char comparison. Using the apostrophe for the 'S' also tells you that you're using 'S' as a char and not as a string.
Your second switch statement isn't using a string, but a single char. Hence, no string comparison.

Categories