How to identify equivalence in a string? [closed] - c#

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 5 years ago.
Improve this question
How can I find equivalent(Not equal) values between strings?
//Equivalent Values
string A = "Beneficiation Return";
string B = "Return Beneficiation";
string C = "Beneficiation From Return";
string D = "Return From Beneficiation";
if i use
if(A == B)//Equal
It will only compare Equal strings and they are equivalent but not equal, is there any way to verify equivalence?
Equivalence can be: shuffled words, have or not linking words(Just
five:For,To,In,From,At.) or be shuffled and with linking words
the code would results in:
("Beneficiation Return" == "Return Beneficiation")True
("Beneficiation From Return" == "Return Beneficiation")True
("Return Beneficiation" == "Return From Beneficiation")True

I think this is what you're looking for..
string a = "Beneficiation Return";
string b = "Return Beneficiation";
string c = "Beneficiation From Return";
string d = "Return From Beneficiation";
bool isSame = !a.Except(b).Any() && !b.Except(a).Any();
The bool isSame will return true because strings a & b contain the same characters.
Compare a with c and it will return false

You could create a helper function: equivalentStrings that accepts both A and B. In that function you could do the following:
Split both strings A and B, and get two arrays of words
Check if they have same count of words (return false if not)
Check each word in arrayA if there is same word in arrayB, if yes remove the word from both arrays if not return false
If arrayA is empty (all words removed) return true.

Related

Compare two strings to a value in 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 2 years ago.
Improve this question
string 1= reportCard.1.GetText();
string 2= reportCard.2.GetText();
string 3= reportCard.3.GetText();
string 4= reportCard.4.GetText();
string 5= reportCard.5.GetText();
How do I write an if statement which check if any of the above values is false. I need to write an or operate and compare to a Y/N value
if ((1||2||3||4).Equals("No"))
This is giving error - "Cannot be applied to operands string"
I'd advise against using == to test string equality. Use String.Equals() instead.
You can also do this in one statement using Linq:
if ((new [] {string1, string2, ...}).Any(s=>string.equals(s,"No",StringComparison.CurrentCultureIgnoreCase)))
{
DoStuff();
}
This will DoStuff() if any of your strings are equal to "no" ignoring the case.
See String.Equals() and Enumerable.Any() for further reading. It should be noted that an Enumerable is any class that can be enumerated, so this includes almost all collections like arrays and lists.
Replace string1,string2,... with all of your string variable names. I'd also advise changing your report card class to have a List<string> of results (assuming all of your results are strings) rather than these fields. That way you could enumerate over it like a collection.
See List<T>.
You also can't have variable names that start with strings.
If you absolutely HAVE to use ORs, you need to perform each comparison separately and then chain them together. The way you've done it essentially reads "if string1 or string2 or string3 or string4 equals "no"". Which will evaluate as though you're saying ((string1 or string2) or (string3 or string4)) equals "no".
Obviously, "apple or pair" isn't a valid operation. So what you want is "string1 equals "no" or string2 equals "no" or string3 equals "no"...
To do this in C# you'd use something like:
if (string1 == "No" ||
string2 == "No" ||
stringN == "No" ||)
{
DoStuff();
}
I'd strongly advise against using this approach though as it's poor practice. Even if it's beyond the scope of your assignment, read up on the links I've posted and try and implement it in a more robust fashion. If this is a school assignment, most teachers will be happy to see a "better" solution than the one they're looking for. Just don't copy and paste the code I've provided and make sure you understand it.
Should rather be like below .. you need to test for the values of each variable and compound their output.
Considering you have your variable defined like below
string a = "No";
string b = "No";
string c = "No";
string d = "No";
You can check
if ((a == "No" ||b == "No" ||c == "No" ||d == "No" )
You can as well use All() method from System.Linq
if((new[] {a,b,c,d}).All(x => x == "No"))
First of all. Your code has some issues:
You cannot name variables just with numbers in C#. You could name them like, v1, v2, v3 etc.
since you want to compare boolean values why you are using string variables? Instead, you could declare your variables as follows: bool v1 = bool.Parse(reportCard.1.GetText());. Here you have to make sure that the string values which come from the object (reportCard) are suitable to boolean values. such as"True" or "False".
Then you can simply write the if statement as follows:
if (!v1 || !v2 || !v3 || !v4):
{
// do smth;
}

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?

Regex find duplicate values in this set [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
I have an list of string values which looks like this:
GREEN,BLUE,BLUE
BLUE,BLUE,GREEN
GREEN,RED,RED
RED,BLUE,BLUE
BLUE,RED,RED
GREEN,BLUE,BLUE
RED,GREEN,BLUE
I will use a foreach to loop through each line and find unique values.
I need a regex that returns true is there are no color duplicates (RED,GREEN,BLUE) and false if there are color duplicates (RED,GREEN,RED).
What would the regex look like?
You can try using Linq instead of regular expressions:
using System.Linq;
...
string source = "BLUE,BLUE,GREEN";
// do we have three distinct items?
bool allDistinct = source.Split(',').Distinct().Count() >= 3;
Test:
List<string> list = new List<string>() {
"GREEN,BLUE,BLUE",
"BLUE,BLUE,GREEN",
"GREEN,RED,RED",
"RED,BLUE,BLUE",
"BLUE,RED,RED",
"GREEN,BLUE,BLUE",
"RED,GREEN,BLUE",
};
var result = list
.Select(source => $"{source,-15} {source.Split(',').Distinct().Count() >= 3}");
Console.Write(string.Join(Environment.NewLine, result));
Outcome:
GREEN,BLUE,BLUE False
BLUE,BLUE,GREEN False
GREEN,RED,RED False
RED,BLUE,BLUE False
BLUE,RED,RED False
GREEN,BLUE,BLUE False
RED,GREEN,BLUE True
Edit: Linq can help out in the generalized case:
bool allDistinct = !source
.Split(',')
.GroupBy(item => item, (k, s) => s.Skip(1).Any())
.Any(item => item);

richtextbox application test c# [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 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.

LINQ- Select linq from string array [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
How apply linq select to string array in C#
ex :
string[] result;
...
result.Select(..)
?
Thanks.
You pass in a lambda function that tells the system what you want to do with each string.
string[] result;
...
var newList = result.Select(s => {do something with s});
The function can do most anything that takes a string as an input and returns a value - it doesn't even have to return a string! For example, if the strings contained numeric characters, you could return a collection of numbers:
IEnumerable<int> newList = result.Select(s => int.Parse(s));
Note that the original array will not be changed.

Categories

Resources