Modify the last letters of words? [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I need to code a program, which changes the last two (or just the last) letter(s) of the inputted word because of some weird grammar rules of the Lithuanian language.
For example, my name is Kazys.
I want a code which could change the last two letters (ys) to another letter (y).
So when a person inputs
Kazys
The output would be
Hello, Kazy.
If a person inputs Balys, the code should change the name to Baly and print it.
I am just a beginner in C#. So, I don't even know some of the basic functions.
Any help is very appreciated!!
P.S. For those who wonder, why do I need this, I can tell you that it's a thing in Lithuanian grammar which requires to change the end of the word if you are addressing somebody.

I, personally, think language rules like this are why regular expressions exist. It allows you to easily make rules with look-aheads, look-behinds, etc., to make sure that the word is only changed if it fits a certain structure. For your example case, it should be as easy as:
var firstName = "Kazys";
var formattedFirstName = Regex.Replace(firstName, #"ys$", "y");
The $ at the end of the string means that it will only change "ys" to "y" when "ys" are the last two letters in a string.
Regular Expressions can get much more complicated and many people don't like them. However, I find them to be concise and clear most of the time.

You can write an extension class that applies the rules stored in a dictionary easy enough. Complicated rules could make Regex a better option, but if simple string replacement, a case insensitive dictionary could be better to avoid checking every possible rule every time.
public static class LanguageExtensions
{
// Define case insentive dictionary
public static Dictionary<string, string> Rules = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
// List rules here
{ "ys", "y"},
};
public static string ApplyRules(this string input)
{
string suffix;
if (input != null && input.Length > 2 && Rules.TryGetValue(input.Substring(input.Length - 2, 2), out suffix))
return input.Remove(input.Length - 2) + suffix;
else
return input;
}
}
Then, you just have to call the extension method:
Console.WriteLine("Kazys".ApplyRules()); // "Kazy"

Minimal working sample of what you might be after.
You seem to have complex requirements to code but, this is the basic concepts of replacing string(s) within a string.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace ChangeLastChar_46223845
{
public partial class Form1 : Form
{
TextBox txtbx_input = new TextBox();
TextBox txtbx_result = new TextBox();
Button btn = new Button();
public Form1()
{
InitializeComponent();
AddOurStuffToTheForm();
PutDefaultWordInInputBox();
}
private void PutDefaultWordInInputBox()
{
txtbx_input.Text = "Krazys";
}
private void AddOurStuffToTheForm()
{
txtbx_input.Location = new Point(5, 5);
btn.Location = new Point(5, txtbx_input.Location.Y + txtbx_input.Height + 5);
txtbx_result.Location = new Point(5, btn.Location.Y + btn.Height + 5);
btn.Text = "Substring";
btn.Click += Btn_Click;
this.Controls.Add(txtbx_input);
this.Controls.Add(btn);
this.Controls.Add(txtbx_result);
}
private void Btn_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtbx_input.Text) || string.IsNullOrWhiteSpace(txtbx_input.Text))
{
return;
}
if (txtbx_input.Text.EndsWith("ys"))
{
txtbx_result.Text = "Hello " + txtbx_input.Text.Substring(0, txtbx_input.Text.Length - 1);
}
}
}
}

Related

Neater Way to Set One of Two Variables to a Certain Value Based on a Boolean? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I've noticed that I use this pattern a lot in my C# code. (It's within a Unity script, if it matters.)
if (someBoolean) {
firstVar = 10;
} else {
secondVar = 10;
}
My question is as simple as can be--is there a way to make this pattern take up less space than the five lines it does? Perhaps even make it inline? I thought ternary operators might do it, like so...
(someBoolean ? firstVar : secondVar) = 10;
...But it quickly became apparent ternary operators in C# don't work like that.
I also considered creating some sort of global function in a static class that I could simply pass the appropriate variable to, but it's the pattern that is frequently repeated, not necessarily the operation. So the function method wouldn't work for where I've repeated this pattern elsewhere, with different operations, like so...
if (anotherBoolean) {
thirdVar += exampleVar;
} else {
fourthVar += exampleVar;
}
Of course, I could just do this...
if (someBoolean) { firstVar = 10; } else { secondVar = 10; }
...But that's kind of icky, isn't it? Either way, I'd appreciate any advice you could provide. Many thanks.
Just use if/else. You--by which I mean I--are/am overthinking it.
You can use Destructuring assignment (C# 7) to make it into single statement:
(firstVar, secondVar) = someBoolean ? (10, secondVar) : (firstVar, 10);
Whether it is more expressive than simple if is up to debate, but it gives you single statement at least. Can be good option if the rest of the project actively uses "destructing" and new C# 7+ features.
Unlike suggestion to use helper function with ref arguments destructing can be used for arrays, lists and properties:
(list[0], list[1]) = someBoolean ? (list[0], 10) : (10, list[1]);
(x.SomeProp, x.OtherProp) = someBoolean ? (x.SomeProp, 10) : (10, x.OtherProp);
If this is a frequent occurrence, you can make use of extension methods as well.
class Program
{
static void Main(string[] args)
{
var firstVar = 1;
var secondVar = 2;
true.SetValue(ref firstVar, ref secondVar);
false.SetValue(ref secondVar, ref secondVar);
Console.Read();
}
}
public static class BoolExtensions
{
public static void SetValue(this bool bVal, ref int first, ref int second)
{
if (bVal)
first = 10;
else
second = 10;
}
}

Is there a programmatic way to identify .Net reserved words? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am looking for reading .Net, C# reserved key words programmatically in VS 2015.
I got the answer to read C# reserved words in the [link][1].
CSharpCodeProvider cs = new CSharpCodeProvider();
var test = cs.IsValidIdentifier("new"); // returns false
var test2 = cs.IsValidIdentifier("new1"); // returns true
But for var, dynamic, List, Dictionary etc the above code is returning wrong result.
Is there any way to identify .net keywords in run time instead of listing key words in a list?
string[] _keywords = new[] { "List", "Dictionary" };
This is a perfectly fine C# program:
using System;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
int var = 7;
string dynamic = "test";
double List = 1.23;
Console.WriteLine(var);
Console.WriteLine(dynamic);
Console.WriteLine(List);
}
}
}
So your premise is wrong. You can find the keywords by looking them up in the short list. Just because something has a meaning does not mean it's in any way "reserved".
Do not let the online syntax highlighting confuse you. Copy and paste it into Visual Studio if you want to see proper highlighting.
As explained by nvoigt, your method of programmatically determining if a string is a keyword is effectively correct. To be complete, (after checking Reflector) it should be:
bool IsKeyword(string s)
{
var cscp = new CSharpCodeProvider();
return s != null
&& CodeGenerator.IsValidLanguageIndependentIdentifier(s)
&& s.Length <= 512
&& !cscp.IsValidIdentifier(s);
}
(The VB.NET version needs 1023 and a check for "_".)

How to address 3 parameters in my method program? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to write a C# code for the problem written below, but whatever I do, I can't figure out how to solve the problem. I guess I can't understand why it should be done the way it is asked! Anyways, this is what I need to do: Start a new console application.
In the Main method, Create a string array of size 5, name the array
Profile. Ask the user to input their first name, But you must do
that by calling a method you will write called GetStringInput This
method should require 3 parameters.
The first is a string, which is the question to ask the user. (For this first usage, you might pass in a string that says "enter your first name")
The second parameter is the Profile array
The third parameter is an int, the index, meaning, in which location in the array the user's answer should be stored.
First question (First name).
Ask the user for their last name, again, by calling that same GetStringInput, but passing in a different question.
Ask the user for their age, again, by calling that same GetStringInput,
but passing in a different question (note that the age will be entered and stored as a string, and not converted to an int)
Ask the user for their favorite color, again, by calling that same GetStringInput, but passing in a different question.
Ask the user for their favorite sport, again, by calling that same GetStringInput, but passing in a different question.
Now call a new method called DisplayProfile. This method should require a string array as a parameter, and you will pass in the Profile array. Add a Console.ReadLine(); statement and your Main method is done.
Now implement the 2 methods that you have been calling, GetStringInput and DisplayProfile. The DisplayProfile method should pull the information out of the array, and write out the values in a reasonable way.
Something like, for example Your name is John Smith, you are 21 years old. Your favorite color is green and your favorite sport is tennis.
Now, I have written this code:
static void Main(string[] args)
{
string[] Profile = new string[5];
GetUserInput(Profile);
DisplayProfile(Profile);
}
private static void DisplayProfile(string[] Showrofile)
{
Console.WriteLine("Your name is {0} {1}, you are {2} years old.\nYour favorite color is {3} and your favorite sport is {4}.",
Showrofile[0], Showrofile[1], Showrofile[2], Showrofile[3], Showrofile[4]);
}
public static string [] GetUserInput(string[] Getprofile)
{
string[] Question = new string[5];
Question[0] = "Enter your First name:";
Question[1] = "Enter your Last name:";
Question[2] = "Enter your Age:";
Question[3] = "Enter your Favorite color:";
Question[4] = "Enter your Favorite sport:";
for (int i = 0; i < Question.Length; i++)
{
Console.WriteLine(Question[i]);
Getprofile[i] = Console.ReadLine();
}
return Getprofile;
}
}
}
I don't know what to do. I appreciate your help!
I have been watching the comments and the other people are right, you should read how to ask the question because it wasn't clear. It does seem some simple Google searches would have answered this question very easily but I will take pity on your hair pulling. Here is an example of what you are asking for.
Sometimes the best approach is to walk away and then come back calm because when you were asking the Gabe how to make a method with three parameters you pretty much answered your own question. See below and good luck, take it slow.
public static void Main()
{
const int TOTAL_QUESTIONS = 5;
string[] profile = new string[TOTAL_QUESTIONS];
string[] questions = new string[]
{
"Enter your First name:",
"Enter your Last name:",
"Enter your Age:",
"Enter your Favorite color:",
"Enter your Favorite sport:"
};
for (int i = 0; i < TOTAL_QUESTIONS; i++)
{
profile = GetUserInput(questions[i], profile, i);
}
DisplayProfile(profile);
}
private static void DisplayProfile(string[] profile)
{
Console.WriteLine($"Your name is {profile[0]} {profile[1]}, you are {profile[2]} years old.\nYour favorite color is {profile[3]} and your favorite sport is {profile[4]}.");
}
//Here is where you put the parameters you told Gabe about.
private static string[] GetUserInput(string question, string[] profile, int index)
{
Console.WriteLine(question);
profile[index] = Console.ReadLine();
return profile;
}
Edit:
Since you brought it up in the comments about the teacher saying GetUserInput doesn't need to return anything you can see how it works. It would look like this.
public static void Main()
{
const int TOTAL_QUESTIONS = 5;
string[] profile = new string[TOTAL_QUESTIONS];
string[] questions = new string[]
{
"Enter your First name:",
"Enter your Last name:",
"Enter your Age:",
"Enter your Favorite color:",
"Enter your Favorite sport:"
};
for (int i = 0; i < TOTAL_QUESTIONS; i++)
{
GetUserInput(questions[i], profile, i);
}
DisplayProfile(profile);
}
private static void DisplayProfile(string[] profile)
{
Console.WriteLine($"Your name is {profile[0]} {profile[1]}, you are {profile[2]} years old.\nYour favorite color is {profile[3]} and your favorite sport is {profile[4]}.");
}
private static void GetUserInput(string question, string[] profile, int index)
{
Console.WriteLine(question);
profile[index] = Console.ReadLine();
}

Designing a simple console trivia application

We have been tasked with designing a C# trivia application as a File I/O exercise. So far, I've got a good start, but the presentation step is kind of stumping me.
I'm starting with a delimited file featuring the following data:
Question;CorrectAnswerA;AnswerB;AnswerC;AnswerD;AnswerExplanation
e.g.,
What color is the sky?;Blue;White;Green;Yellow;The sky is blue.
The game will display the question and the four answers from which the user can select.
What Color is the Sky?
A. Blue
B. White
C. Green
D. Yellow
Select A, B, C, or D:
Unfortunately, for ease of populating the dataset, A is always the correct answer. I want to randomize the order in which the four answers display, but the program still needs to know which was the correct answer. I also need to have a user input of A, B, C, or D tie back to a specific instance of an answer to compare the selectedAnswerString to the correctAnswerString.
I've been playing with an array of the four answers which are randomly populated, but I can't wrap my head around how to flag something as correct based on the user's choice; my logic to do or assign that always seems to fall out of scope or duplicate across all four records in the array.
Other students I've talked to said they created their datasets with the answers pre-scrambled (so they can just print them in the order read) with a FIFTH answer field for the correct answer. While definitely an EASY way to make it happen, I don't think it's as elegant as my strategy.
Should I just change the input dataset? does anyone have any ideas on a good way to pursue my idea for the randomization?
Create a class called Question with properties: int Id, string QuestionText, List<string> Answers, string CorrectAnswer
Or, as step forward, also create class Answer with Id and Value and reference to it.
public class Question
{
public int Id;
public string QuestionText;
public List<Answer> Answers;
public Answer CorrectAnswer;
}
public class Answer
{
public int Id;
public string Value;
}
Afterwards populate this structure and randomize when printing
Keep track of the correct answer using a separate variable. Then use Fisher-Yates to shuffle your array:
Random random = new Random();
void Shuffle(string[] answers) {
for (int i = 0; i < answers.Length - 1; i++) {
int j = random.Next(i, answers.Length);
string temp = answers[j];
answers[j] = answers[i];
answers[i] = temp;
}
}
After the user responds, just compare their selection with the correct answer you've saved.
Try defining your data structure for a question in this way:
public class Question
{
public string Question;
public string[] Answers;
public int CorrectAnswer;
public string CorrectAnswerExplanation
}
This way you can scramble the strings in the array Answers, while still keeping track of the index of the correct answer in CorrectAnswer.
Alternatively if you can't use a separate class to model the question (this is a homework question so maybe you have not learned this yet), you can use a predetermined position in the array (the 1st or the 5th element) to hold the index of the correct answer. So your array for answers would look like:
"Blue", "White", "Green", "Yellow", "0"
Step 1: Define a data structure. Others have already given you a structure so use that.
Step 2: Populate your data structure. You could System.IO.File.ReadLines and parse each line - I assume you have this bit handled already.
Step 3: Randomize the order of your answers. For this, assuming you have your structure:
public static void RandomiseAnswers(IEnumerable<Question> questions)
{
var rand = new Random((int)DateTime.Now.Ticks);
foreach (var question in questions)
{
question.Answers = question.Answers.OrderBy(x => rand.Next()).ToArray();
}
}
Step 4: Recieve gold star from teacher for your outstanding work
Personally I'd put a boolean in the Answer class defaulting to false. This way when the answer is selected you can read whether it's correct or not.
public class AskQuestion
{
public int Id;
public string Question;
public string Explanation;
public List<Answer> Answers = new List<Answer>();
}
public class Answer
{
public bool Correct = false;
public string Value;
}
now when you randomize the list the correct answer is automatically identified
One way to use these classes would be like this:
static void Main(string[] args)
{
StreamReader sr = new StreamReader("text.txt");
List<AskQuestion> Questions = new List<AskQuestion>();
Random rnd = new Random(DateTime.Now.Millisecond);
//Loop through the file building a list of questions
while(!sr.EndOfStream)
{
AskQuestion NewQuestion = new AskQuestion();
string[] input = sr.ReadLine().Split(';');
NewQuestion.Question = input[0];
NewQuestion.Explanation = input[5];
for(int i = 1; i < 5; i++)
{
Answer NewAnswer = new Answer();
NewAnswer.Value = input[i];
NewQuestion.Answers.Add(NewAnswer);
}
//The first question is always correct so set its boolean value to true;
NewQuestion.Answers[0].Correct = true;
//Now ranmdomize the order of the answers
NewQuestion.Answers = NewQuestion.Answers.OrderBy(x => rnd.Next()).ToList();
Questions.Add(NewQuestion);
}
//Generate menu and get response for each question
foreach(AskQuestion q in Questions)
{
Console.WriteLine(q.Question + ":\n\tA - " + q.Answers[0].Value + "\n\tB - " + q.Answers[1].Value + "\n\tC - " + q.Answers[2].Value + "\n\tD - " + q.Answers[3].Value + "\n");
char input = '0';
while(input < 'A' || input > 'D')
{
input = char.ToUpper(Console.ReadKey().KeyChar);
if(input >= 'A' && input <= 'D')
{
//Use the boolean value in the answer to test for correctness.
if(q.Answers[input - 'A'].Correct)
{
Console.WriteLine("\nCorrect\n");
}
else
Console.WriteLine("\nWrong\n");
Console.WriteLine(q.Explanation);
}
}
}
Console.ReadLine();
}

how to concatenate a - in a string c# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
i am trying to make a calculator in c# and i am looking to concatenate a - into a string or something similar. the expected output should also minus the two variables. EX,
string ready;
private void minus_Click(object sender, EventArgs e)
{
long minusnumber = 32;
ready = minusnumber + "-";
}
.
.
.
private void equals_Click(object sender, EventArgs e)
{
long equalsNumber1 = 32;
ready += equalsNumber1;
MessageBox.Show(ready);
}
and console output would be 0
but it is taking "-" as minus not subtracting the two numbers.
ive tried escaping it (not sure if i did escape it right) and it didn't help:/
use
string.concat(minusnumber , "-");
It might help you. You can use n numbers of object on concat method.
I think this might be what you are hoping to accomplish, but it is a bit unclear. This will take minusnumber and negate it. So then when you add previous number to minusnumber, it will in effect subtract. Only problem with this is your ready variable appears to be a string.
private void minus_Click(object sender, EventArgs e)
{
long minusnumber = 32;
ready = -minusnumber;
}
Perhaps ready should be a long. When you are getting user input, you can use TryParse:
string userText = "54";
long userInput;
Int64.TryParse(userText, out userInput);
ready -= userInput;
From what you've written, the variable ready in minus_Click is local to minus_Click and not the global you probably intended it to be.
Instead of:
string ready = minusnumber + "-";
Perhaps you meant:
ready = minusnumber + "-";
EDIT
Now that the question is patched, it seems that the real question is "Why does MessageBox.Show(ready); show "32-32" instead of 0?" If that is the question, the reason is you are showing the value of the variable ready. This is a string. You started it at "32-" then added "32". The result of this string concatenation is "32-32". In order to perform arithmetic evaluation you need to write the code to parse the string and do the evaluation. Or find someone that has written an Eval() method for strings containing arithmetic expressions.
For make calculator you must use Polish Notation or RPN

Categories