String comparison issues - c#

I needed to compare two strings, if any one of them contains other in C#. If suppose we have following string patterns
string str1 = "Hello World Test";
string str2 = "Hello World";
string str3 = "Hello World Test Example";
string str4 = "No match";
so following function is required
Compare(str1,str2) = true;
Compare(str1,str3) = true;
Compare(str1,str4) = false;
I am trying following, but looking for if there is some more better alternatives available
if (str1.Contains(str2) || str2.Contains(str1))
Is there a way to make that check with a single call?

Check for the length of the strings and always use contains in such a way that shorter string should be looked out in the longer string.You can use str1.Contains(str2).

Related

How to get the string data which is outside of parenthesis in C#

I need to get the data which is outside of parenthesis
string data = "English(Language)";
string result= "English";
The result should display the text "English".
I tried with Regex but not able to get the desired result.
Easiest solution that I can think of:
string data = "English(Language)";
string result = data.Substring(0, data.IndexOf('('));
That is of course, if you never need the data within the parenthesis.
Another way to do it is by using String.Split:
string data = "English(Language)";
string result = data.Split('(')[0];
This is marginally slower than the first example since it needs to allocate memory for an array.
The third way to do it is via regular-expressions:
string data = "English(Language)";
var pattern = new Regex("(\\w+\\s?)\\((\\w+)\\)", RegexOptions.Compiled);
string result = pattern.Match(data).Groups[1].Value;
This is the slowest of all the examples, but captures both "English" and "Language". It also allows for whitespace \s? between English and (Language).
A great tool for testing regular expressions is RegexPal, just remember to escape everything when you move it over to C#.
Here is a fiddle, testing the performance of all options.
Try:
string input = "English(Language)";
string regex = "(\\(.*\\))";
string output = Regex.Replace(input, regex, "");
You will need that:
using System.Text.RegularExpressions;
If you dont bother to use Regex, the below solution works fine.
string data = "English(Language)";
string result = Regex.Match(data, #"(.*)\(.*\)").Groups[1].Value;
Console.WriteLine(result); // English
Hi take a look at the Split methods:
string data = "English(Language)";
string result= "English";
var value = data.Split('(').First();
Console.WriteLine (value);
Result :
English
xd or just:
string data = "English(Language)";
string result = data.Replace("(Language)", "");

Does String.Replace() create a new string if there's nothing to replace?

For example:
public string ReplaceXYZ(string text)
{
string replacedText = text;
replacedText = replacedText.Replace("X", String.Empty);
replacedText = replacedText.Replace("Y", String.Empty);
replacedText = replacedText.Replace("Z", String.Empty);
return replacedText;
}
If I were to call "ReplaceXYZ" even for strings that do not contain "X", "Y", or "Z", would 3 new strings be created each time?
I spotted code similar to this in one of our projects. It's called repeatedly as it loops through a large collection of strings.
It does not return a new instance if there is nothing to replace:
string text1 = "hello world", text2 = text1.Replace("foo", "bar");
bool referenceEqual = object.ReferenceEquals(text1, text2);
After that code executes, referenceEqual is set to true.
Even better, this behavior is documented:
If oldValue is not found in the current instance, the method returns the current instance unchanged.
Otherwise, this would be implementation-dependent and could change in the future.
Note that there is a similar, documented optimization for calling Substring(0) on a string value:
If startIndex is equal to zero, the method returns the original string unchanged

How to check if string contains the text in C# Winforms

Can anyone help me in writing a piece of code in C# Winforms, which can give me a boolean value, that whether a piece of string contains a few words.
For example, If I want to check whether string test only string exists in string "Data is provided to test only string".
I have written following piece of code, but it alwys gives me true, whether string contains the words or nor.
private bool ContainsText(string input)
{
for (int i = 0; i < input.Length; i++)
{
if (((int)input[i] >= 65 && (int)input[i] <= 90) || ((int)input[i] >= 97 && (int)input[i] <= 177))
return true;
}
return false;
}
When I call the following line, I always get true, which is not correct
MessageBox.Show(ContainsText("test only string").ToString());
Code-wise, your ContainsText code immediately returns true if any character in input is either in "A to Z" or "a to U+00B1" for some reason.
But the problems lie deeper than that: you've described two inputs - the string to check for, e.g. "test only string" and the string to check for its presence, e.g. "Data is provided to test only string". Your method only accepts one input, and doesn't use any other state. So it can't possibly work. It's worth taking a step back and trying to work out why you didn't notice that you needed two inputs - and why indeed your test only used "test only string" and didn't mention "Data is provided to test only string".
You don't really need a method at all though - String already has a Contains method:
if (textToCheck.Contains(textToFind))
{
...
}
That's assuming you want an ordinal comparison. Use IndexOf with an appropriate StringComparison if you want to check in a culture-sensitive or case-insensitive way.
You can use Contains method of String object.
var a = "Data is provided to test only string";
var b = "test only string";
if (a.Contains(b))
MessageBox.Show("yes");
A simple string.IndexOf perhaps with the enum to ignore case:
string myTestString = "Data is provided to Test Only String";
if(myTestString.IndexOf("test only string", StringComparison.CurrentCultureIgnoreCase) >= 0)
Console.WriteLine("Found text");
Of course the string class has also a Contains method, but it is implemented as a call to IndexOf, without the possibility to ignore the case.
public bool Contains(string value)
{
return (this.IndexOf(value, StringComparison.Ordinal) >= 0);
}
Use IndexOf
http://www.dotnetperls.com/indexof
example of usage..
string str = "string to test";
bool result = str.IndexOf("The hosted network started.") != -1;
MessageBox.Show(result.ToString());

why use string constructor with char array for constants?

I found this piece of code and I'd like to understand why the developer used the string constructor with a char array instead of just a literal constant string:
static string atomLang = new String("lang".ToCharArray());
The only reason I can think of is to avoid getting a reference to the interned instance of the string.
string str1 = "lang";
string str2 = "lang";
string str3 = new String("lang".ToCharArray());
Console.WriteLine(object.ReferenceEquals(str1, str2)); // Output: true
Console.WriteLine(object.ReferenceEquals(str1, str3)); // Output: false
Not that this will have any practical effects on your code (other than marginal performance differences).

Extract strings from string

Ill lose to much time since i don`t have too much experience in manipulating with strings/chars.
i have
string original = "1111,2222,"This is test work")";
i need
string first = "1111";
string second = "2222";
string name = "This is test work";
C# ASP.NET
Use string.Split() - your pattern is simple (split on comma), there is no need to use a RegEx here:
var parts = original.Split(',');
first = parts[0];
second = parts[1];
name = parts[2].TrimEnd(')'); //in case you really wanted to remove that last bracket
Use the String.Split method:
string[] values = original.Split(new Char [] {','});
This will break apart your string at every comma and return a string array containing each part. To access:
string first = values[0];
string second = values[1];
string name = values[2];

Categories