richtextbox application test c# [closed] - c#

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 7 years ago.
Improve this question
I'm very new to c#. I created a forms. A richtextbox and a button in it.
I have a list of operators: Sum, Subtract,Multi,Div.I want to run a small richtextbox test. For example,in the richtextbox I write a text (eg. Sum(1,2)) and then click the button. A return result(eg.3) prints in the richtextbox.
My idea is to use string contains
foreach( var element in operatorlist)
{
string text=richtextbox.text;
if( text.contains(element)== true)
{
element(parameter1,parameter2);//something like this
}
}
I met two questions right row.
My first question is how to get the mathematical operation from the richtextbox text. Is there a better way than mine?
My second question is once we know the operator,how to allocate the two parameters in the richtextbox to the operator.
I'm not asking for coding, I'm just looking for ideas. If you have a good idea and wish to share.

You can evaluate an expression using the DataTable.Compute function:
int p1 = 1 ; string s1 = p1.ToString() ;
int p2 = 2 ; string s2 = p2.ToString() ;
int p3 = 3 ; string s3 = p3.ToString() ;
// Compute (p1+p2)*p3 ==> 9
int result = new DataTable().Compute( "("+s1+"+"+s2+")*"+s3+")","") ;
or directly:
string expression = "(1+2)*3" ;
int result = new DataTable().Compute(expression,"") ;

I think this comes down to personal style. Your way will definitely work, so good on you for that. The way I would do it is to create a Dictionary of strings to an enum. So for example, said dictionary and enum might look like this:
enum Operator { Addition = 0, Subtraction = 1, Multiplication = 2, Division = 3, etc};
var operatorDictionary = new Dictionary<string, Operator>()
{
{"Addition", Operator.Addition},
{"Subtraction", Operator.Subtraction},
etc...
};
Then to get the value you would just do
Operator operation;
operatorDictionary.TryGetValue(string operationString, out operation);
and you would have to then build some code that switches through the Operators and performs the correct operation. There is even a way of converting a string to an enum, so that would work as well.
It looks like the parameters are in a consistent format, so you would just make a simple method that splits by parenthesis and the comma, and returns the strings that it found.
Let me know if you need anything explained more.

Related

How to convert 2 properties of every record in a List from string to int(by extracting numbers from string) C# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Currently, I have a List of objects. Each record has three properties.
HEID = string type,(The string always looks like 12R,27L,36)
LEID = string type,(The string always looks like 12R,27L,36)(I want to
extract the numbers and set them as an int.)
RunwayId = int,
I want to take the HEId and LEId strings, and extract the numbers, and store it as a new List, or change the current properties to int type with converted values.
I am looping through the list, and this is where I want to convert each record's string type property to int type.
Thanks
yourList.Select(obj => new { HEID = float.Parse(obj.HEID), LEID = float.Parse(obj.LEID) });
this will return an IEnuramble of anonymous objects
you can also create new type with these properties as int and instead of selecting an anonymous type u can cast or select to the new type
yourList.Select(obj => new NewTypeWithInt { HEID = float.Parse(obj.HEID), LEID = float.Parse(obj.LEID) });
or even cleaner you can create a cast opreator
yourList.Select(obj => (NewTypeWithInt)obj);

How to find closest string in list [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 5 years ago.
Improve this question
How to find closest string(s) in list:
var list = new List<string>
{
"hello how are you",
"weather is good today",
"what is your name",
"what time is it",
"what is your favorite color",
"hello world",
"how much money you got",
"where are you",
"like you"
};
and if updated input is:
string input = "how are you";
and another one with type error:
string input = "how are ytou";
For both cases would be good to get this:
hello how are you
where are you
or even this result:
hello how are you
where are you
how much money you got
or at least just:
hello how are you
I need it to avoid minimal type error in user request to make response.
A simple approach would be to use String.Compare to get the
lexical relationship between the two comparands
Order your available items after comparing with the input and take the best match like
string bestMacht = list.OrderBy(s => string.Compare(s, input)).First();
This is only the first approach because the order of words should be ignored. Let's improve this to a full solution. After splitting the strings
string[] splittedInput = input.Split(' ');
you are able to compare the single words using a IEqualityComparer. You are free to define how many characters are possible to fail every word (in this case 2).
private class NearMatchComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
return string.Compare(x, y) < 2;
}
public int GetHashCode(string obj)
{
return obj.GetHashCode();
}
}
Use this comparer and compare the words of the input and your dictionary. If two words (define it like required) are matching (whatever order) select the string.
List<string> matches = list.Where(s => s.Split(' ')
.Intersect(splittedInput, new NearMatchComparer()).Count() >= 2)
.ToList();
The result is a list of potential matches.
I would use a Levenshtein distance. This gives you a value of how different strings are. Just choose the min distance of your set.
How to calculate distance similarity measure of given 2 strings?

Replace string C# not working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
i have two string variables named X and Y respectively. What i want is to replace the X string from the Y variable. I'm using the command string.replace put nothing comes through.
the code i'm using is shown below,
thanks
Stavros Afxentis
string Y= string.Empty;
string X= string.Empty;
Y= get_y_value(...); // my method to get string y
X= get_x_vale(...); // my method to get string X
Y= Y.Replace(X, "");
// i also used Y= Y.Replace(X.ToString(), "");
// but the result is the same
Replace is used to change a "word" inside another string. Like so:
string badString = "Can I has the code";
string goodString = badString.Replace("has", "have");
Your biggest problem is that both strings are Empty.
The code should work flawlessly it will remove the string X because you are replacing it with 0 length string, there might be 2 reasons why this isn't working,
1) X not found in Y
2) You didn't print or show the updated Y
finally i used the code below, where i converted the string to char array and i removed the unwanted text.. pseudocode below:
int i=0;
while ((i<Y.Length) && (counter<1))
{
//ignore part of the string
// and save the position of the char array i want
}
while (poss<Y.Length)
{
new_ch[poss] = ch[poss] //save the array to new char array
}
string y_new = new string(new_ch);

Reading a text file and assigning certain lines to certain variables [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 8 years ago.
Improve this question
I'm working on a Trivia C# console game which reads a text file that has a question , answer multiple choices ,the number of the correct choice and answer explanation.There is four question sets .The task is to prompt each question in the file to the console window ,have the user enter the answer then compare the user's answer with the correct one.That should be done for all four questions in the file.
A class that includes question ,multipleAnswewrChoice,correctAnswer and answerExplanation has been created with getters and setters for each field .
What I'm struggle with is how after reading the file ,to assign each question to a certain variable in order to prompt it to the user and also to do this for four sets.
I made an array of size 4 (as I have 4 lines for each question set) to store the lines then assigned each element to each variable above ,but I couldn't figure out how to loop to do the same for all four sets.
The QuestionUnit is the class that contains the question fields.
public void ReadQuestionFile( QuestionUnit unit)
{
string[] arrayReader = new string[4];
string line = "";
int i = 0;
string fileName = "TextFile1.txt";
StreamReader myReader = new StreamReader(fileName);
while ((line = myReader.ReadLine()) != null && i < 4 )
{
arrayReader[i] = line;
// Console.WriteLine(line);
//Console.WriteLine(arrayReader[i]);
i++;
}
unit.M_Question = arrayReader[0];
unit.M_Answers = arrayReader[1];
unit.M_CorrectAnswers = arrayReader[2];
unit.M_Explanation = arrayReader[3];
}
Any ideas about how to do this ?
Because all your data is in the same file, your going to need to take a slightly different approach. Instead of passing in the item to fill out, I would have the function return the list of read questions:
public IEnumerable<QuestionUnit> ReadQuestionFile()
Then, read in a loop until you reach the end of the file. This approach is NOT safe for invalid input, so be careful:
string fileName = "TextFile1.txt";
List<QuestionUnit> readQuestions = new List<QuestionUnit>();
using (StreamReader myReader = new StreamReader(fileName))
{
while (!myReader.EndOfStream)
{
QuestionUnit newQuestion = new QuestionUnit();
newQuestion.M_Question = myReader.ReadLine();
newQuestion.M_Answers = myReader.ReadLine();
newQuestion.M_CorrectAnswers = myReader.ReadLine();
newQuestion.M_Explanation = myReader.ReadLine();
readQuestions.Add(newQuestion);
}
}
return readQuestions;
Basically, you read until the end of the file, reading four lines at a time. You'll get some null values if the input format isn't correct. You don't really need an array here since you can store the values directly in your object, which you then add to the list when you are done populating it (technically you could have done it before as well). Then you return the filled out list to whatever uses it.
You could possibly use a yield return instead of directly adding to a list, but that is a bit of an advanced concept for starting out, and I'm not sure how well it would mesh with the File I/O. It is good to be aware of its existence either way. The only change would be the removal of readQuestions, and the line:
yield return newQuestion;
where the call to Add currently is.
Let me know if I can clarify anything!

Getting sub string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
The question is on C#.
I have a string "value1=1234;value2=2345;value3=3456;value4= ..."
What is the best way to retrieve the values?
I thought about String.Split(";") but I don't know how to retrieve the values only. The result I get includes the prefix I don't want.
I only want the values of "1234", "2345", "3456"... nothing else, and them put them into a list of strings.
How do I solve this? Thanks.
If the format is always fixed, you can do it fairly easily via LINQ:
List<string> values = theString.Split(';').Select(s => s.Split('=')[1]).ToList();
Note that you may want to use RemoveEmptyEntries if your input string ends in a semi-colon:
List<string> values = theString
.Split(new[]{';'}, StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Split('=')[1]).ToList();
This would prevent an exception from occuring within the Select. If the input doesn't end in a semi-colon, however, this wouldn't be necessary.
var text = "value1=1234;value2=2345;value3=3456;value4= ...";
var pieces = text.Split('=');
var values = new Dictionary<string,string>();
for(int index = 0; index < pieces.Length; index += 2)
{
values.Add(pieces[index], pieces[index + 1]);
}
This will give you a dictionary of the pairs where the key is the left-hand side of the '=' and the value is the string representation of the value, which allows your to do:
var value1 = values["value1"];
var value2 = values["value2"];

Categories

Resources