How do I use char with strings in C#? [duplicate] - c#

This question already has answers here:
How to read char from the console
(4 answers)
Closed 4 years ago.
so the sample code of what I've done is here:
char regular = 'r';
char premium = 'p';
Console.WriteLine("Please enter your service (r or p:");
I am trying to get the user to input either r or p for the service they are have, but I don't know what to put under the "Console.WriteLine" to make it work with the char data types I entered. How do I fix this?
Also, specifically for the entering your service, it has to be in char, so says the problem that I'm working on.
edit*: I have tried using something like...
Console.Writeline("Please enter your service(r or p):")'
r= Convert.ToInt32(Console.ReadLine());
but because it's in char, I have a problem, I'm just not fully sure how to implement this in a way where I can get the user to type r or p
Thanks!

I would suggest to use string instead of char. Something like:
string regular = "r";
string premium = "p";
Console.WriteLine("Please enter your service (r or p:");
var input = Console.ReadLine();
if (input == regular )
{
//your reg logic here
}
else if (input == premium)
{
// your premium logic here
}
else
{
//handle case that none of above entered
}

You can ask for a single character of input from the user with Console.ReadKey()
This returns a ConsoleKeyInfo object which has a KeyChar property that will give you a character
char regular = 'r';
char premium = 'p';
Console.WriteLine("Please enter your service (r or p:");
var keyEntered = Console.ReadKey();
Console.WriteLine("\nYou chose " + keyEntered.KeyChar);

Related

How to remove a series of individual letters from a string?

Messing around with C# logic, trying to build a program where the user inputs a string, and then has the option to decide which letter is removed from said string.
Console.WriteLine("Please enter a string of letters");
string input = Console.ReadLine();
Console.WriteLine("please enter letters you would like removed");
char removedLetters = Convert.ToChar(Console.ReadLine());
foreach (char letter in input)
{
Console.WriteLine(input.Replace(removedLetters,' ').ToLower());
}
This works, but not entirely. I will get rid of characters, but only when written in a specific way that corresponds with the original input.
e.g helloworld -> remove l = he owor d
but helloworld -> remove elo = failure.
Can someone share some knowledge? Really trying to get better at logic, happy i got this far just need bit of guidance.
Cheers,
Andy
Expanding on Jasen's comment from earlier something like this ...
Console.WriteLine("Please enter a string of letters");
string input = Console.ReadLine();
List<char> input_array = input.ToList();
Console.WriteLine("please enter letters you would like removed");
string removedLetters = Console.ReadLine();
char[] remove_array = removedLetters.ToArray();
for (int k = 0; k < remove_array.Count(); k++)
{ input_array.RemoveAll(r=>r== remove_array[k]); }
Console.WriteLine(new string(input_array.ToArray()));
Again, using Linq, in this case RemoveAll, to automate the heavy lifting. I have not tested how efficient these are, they are quick and simple solutions not necessarily the most efficient.
Not sure how you want to handle duplicates but C# has an Except operator that works on Arrays. So convert both strings to an array and something like this should work...
Console.WriteLine("Please enter a string of letters");
string input = Console.ReadLine();
char[] input_array = input.ToArray();
Console.WriteLine("please enter letters you would like removed");
string removedLetters =Console.ReadLine();
char[] remove_array = removedLetters.ToArray();
char[] leftover_array = input_array.Except(remove_array).ToArray();
Console.WriteLine(new string(leftover_array));

Filling an array with fillers in C#

I want the user to first type a code (e.g. fkuk3463kj)
The array is limited to 20.
The rest must be filled with fillers.
Which filler the customer will use (e.g. #, t, z,7,_,0) is his own choice and he will asked to define it at the beginning right after the question for the code.
(hint: afterwards (or if possible directly) I have to decide (to complete the wish of customer) whether the filler has to be at the beginning or at the end.
(for example: fkuk3463kj########## or ##########fkuk3463kj)
Now I don't know how to implement this. I know, that it's not that difficult, but I don't get it! All my tryings were not really succesful.
Could anybody help me? This would be perfect!
And many thx in advance!
Console.WriteLine("Please type in your company number!");
string companyNr = Console.ReadLine();
string[] CNr = new string[companyNr.Length];
Console.WriteLine("Type a filler");
string filler= Convert.ToString(Console.ReadLine());
string[] fill = new string[filler.Length];
.
.
.
.
.
(please pardon my english...)
As far as I can see, you're working with string:
// Trim: let's trim off leading and trailing spaces: " abc " -> "abc"
string companyNr = Console.ReadLine().Trim();
which you want to Pad with some char up to the length length (20 in your case):
int length = 20;
string filler = Console.ReadLine().Trim();
// padding character: either provided by user or default one (#)
char pad = string.IsNullOrEmpty(filler) ? '#' : filler[0];
// shall we pad left: "abc" -> "##abc" or right: "abc" -> "abc##"
// I have to decide (to complete the wish of customer)
//TODO: whether the filler has to be at the beginning or at the end
bool leftPad = true;
string result = leftPad
? companyNr.PadLeft(length, pad)
: companyNr.PadRight(length, pad);
// in case you want a char array
char[] array = result.ToCharArray();
// in case you want a string array
string[] strArray = result.Select(c => c.ToString()).ToArray();
Since you are getting strings as an input you can use string padding. Look here: Padding Strings in the .NET Framework
You can write some method (or extension method):
string AppendString(string str, int count, char filler, bool fromStart)
{
return fromStart ? str.PadLeft(count, filler) : str.PadRight(count, filler);
}
I think this code should work for you.
Console.WriteLine("Please type in your company number!");
string companyNr = Console.ReadLine();
Console.WriteLine("Type a filler");
string filler= Convert.ToChar(Console.ReadLine());
string fill = companyNr.PadLeft(20,filler);
// or use string fill = companyNr.PadRight(20,filler);
Welcome to StackOverflow. I am also a beginner :)
int fixedLength = 20;
string mockupInput = "bladjiea";
string filler = "-";
While(mockupInput.Length < fixedLength)
{
mockupInput += filler;
}
This is easy beginner code that should work.
Lets make this a contest on who will write most beautiful code:
I'll start with the most trivial, brute method XD.
If you have the number:
int fillLength = 20 - companyNr.Length; //for example, 20 chars total.
You can fill a StringBuilder in a loop:
var sb = new StringBuilder()
for (int c = 0; c < fillLength; c++)
sb.Append(filler);
string result = companyNr + sb.ToString();

C#. Input string was not in a correct format

I'm new in the community and I'm learning C#. I try to write a program and faced with the problem below. I tried to find the answer in Google and here but no luck yet. When I choice "Y" I'm getting the error.
I attached the code and screenshot, please help if you can, thank you!
using System;
namespace YourAge
{
internal class Age
{
public static void Main()
{
DateTime newDataTime = DateTime.Now;
Console.WriteLine("So, today is " + "{0}", newDataTime);
Console.Write("Do you smoke a cigarettes? Y/N: ");
char Y = (char)Console.Read();
if (Char.IsUpper(Y))
{
Console.Write("How many cigarettes do you smoke in the day?: ");
int cigTotal = Convert.ToInt16(Console.ReadLine());
//cost of one cigarettes
float costOneCig = 0.3F;
float sumTotal = cigTotal * costOneCig;
Console.WriteLine("You are losing every day:{0:C2}", sumTotal);
}
else
//coming soon
Console.ReadKey();
}
}
}
This is the exception thrown:
The problem is that you are using Console.Read() instead of Console.ReadLine().
Console.Read() only reads the next character from standard input. Console.ReadLine(), on the other hand, reads the entire line of characters from the standard input stream and then moves to the next newline.
When you press 'Y' and then enter, when you get up to the next Console input, Convert.ToInt16(Console.ReadLine(), the Console is still up to the previous input line.
Possible solutions:
Change (char)Console.Read() to Covert.ToChar(Console.ReadLine()). ReadLine takes in an entire string, not a char, so you need to use Convert.ToChar instead of the simple (char) cast to convert the first character of the string into a char.
Add a blank Console.ReadLine() after (char)Console.Read() to tell the Console to flush to the next line.
Input your character together with the next number like "Y2" (although I highly doubt this is what you want to do).
string userInput = Console.ReadLine();
int numberOfCigarettes = Convert.ToInt16(userInput);
This might make it more visible for you what is the problem.
Console.ReadLine() returns a string which you later need to convert into an integer. If your userInput string is not a number, then conversion is impossible and an exception is thrown.
On the other hand your if statement is incorrect as well. Right now you are only checking the variable Y whether it is uppercase not whether it holds a literal character 'y'.
You could for example make sure that the variable Y is always uppercase like this:
if(Y.ToUpper().Equals('Y'))
You may want to try something like this so you can diagnose the problem. Please make sure to mark an answer if it is correct.
Console.Write("Do you smoke a cigarettes? Y/N: ");
string answer = Console.ReadLine();
while (answer.Length != 1) {
Console.WriteLine("Character is one letter silly.");
Console.Write("Do you smoke a cigarettes? Y/N: ");
answer = Console.ReadLine(); }
char response = answer[0];
if (response == 'Y' || response == 'y')
{
//YES RESPONSE
}
else
{
//NO RESPONSE
}
Console.ReadLine();
This code will let you know if you input anything else other than one character. Good luck with C#!

Console.ReadLine() accept one char and stop prompt

In a console application,
I use a Console.Readline() to prompt,
It is only use to get an int (1 to 5),
However you can add more char than necessary.
How could I stop the prompt after record one char in my console please ?
You see this underscore _ .
I don't want to see it anymore.
Edit 01/10/15 10pm :
do
{
string ChoixString = Console.ReadLine();
Analyseur = int.TryParse(ChoixString, out ChoixInt);
} while (!Analyseur || ChoixInt <= 0 || ChoixInt >= 6);
Final goal : The user can't write more than one char in the prompt.
Solution :
ConsoleKeyInfo ChoixKey = Console.ReadKey();
string ChoixString = ChoixKey.Key.ToString();
Analyseur = int.TryParse(ChoixString, out ChoixInt);
Thanks for the help.
use this:
Console.ReadKey();
will read just one character/keypress

Characters not returning

How to fix the errors with characters in C# Employee class I am making. I know how to handle string, int, and double. The char.Parse doesn't cooperate.
public static string AskForLastName()
{
string inValue;
Console.Write("Enter last name: ");
inValue = Console.ReadLine();
return inValue; //works fine
}
public static char AskForGender()
{
char inValue;
Console.Write("Enter gender: ");
inValue = Console.ReadLine();//error here for some reason
return (char.Parse(inValue));//error here for some reason
}
public static int AskForNoDependendents()
{
string inValue;
Console.Write("Enter the dependents: ");
inValue = Console.ReadLine();
return (int.Parse(inValue));//works fine
}
public static double AskForAnnualSalary()
{
string inValue;
Console.Write("Enter annual salary: ");
inValue = Console.ReadLine();
return (double.Parse(inValue));//works fine
}
Console.ReadLine() returns a string. You can't implicitly convert that to a character- what if someone enters "Male" or " M" (preceded by one or more spaces).
Your AskForGender method is going to need to be smarter about what input it accepts, and how it parses that input.
If you really need a character out of this (to satisfy the assignment, or whatever), then you need to figure out a way to get from all of the possible String inputs ("Male", "MALE", "Female", "Horse", "Dog", "4", etc.) to either:
An acceptable Character (presumably 'M' or 'F', but maybe others?)
or
An error condition, whereupon maybe you print a nice error message and ask them to re-enter?
Description
Console.ReadLine returns a string. You can use string[] to get the first character of your string. But you have to make sure that the user inserts at least one character.
Sample
public static char AskForGender()
{
while (true)
{
Console.Write("Enter gender (m/w): ");
string inValue = Console.ReadLine();
// check that the user inputs a character
if (!string.IsNullOrEmpty(inValue) && (inValue[0] == 'm' || inValue[0] == 'w'))
return inValue[0];
}
}
Update
My sample covers now that the user inputs m or w.
Update
It is homework so...
If your Teacher ask "But what happens if the user inputs a M instead of m? You should say "It asks the user again".
If your Teacher asks then "How to make it possible to accept M and m? You should say i can make it case insensitive.
Sample
You should use i can use .NET's .ToUpper() method.
.ToUpper() - Returns a copy of this string converted to uppercase.
public static char AskForGender()
{
while (true)
{
Console.Write("Enter gender (m/w): ");
string inValue = Console.ReadLine();
// check that the user inputs a character
if (!string.IsNullOrEmpty(inValue) && (inValue.ToUpper()[0] == 'M' || inValue.ToUpper()[0] == 'W'))
return inValue.ToUpper()[0]; // returns M or W
}
}
You're trying to pull a string into a char. Console.ReadLine() returns a string.
If you need specifically one character (Presumably M or F) consider making your inValue a string, trimming it (to ensure there are no leading spaces), and then returning inValue[0] (which should be a char)
Something like:
string inValue = Console.ReadLine();
inValue = inValue.Trim();
return inValue[0];
**Note- that's not the best way to do it, but it should make the idea fairly clear.
According to MSDN ReadLine returns a string - you can't assign a string to a char!

Categories

Resources