List and array comparison - c#

I have a requirement wherein I have a value in Viewbag.Keyword like "Johnson and Jen" so I have to split this value and compare it with List.
I was trying the below code but facing error some or the other way(eg; this is char not string and so on) and it doesn't look like smart coding as per latest functionalities available in framework 4.5
var str = Convert.ToString(ViewBag.Keyword);
string[] str1 = str.Split(' ');
for (int j = 0; j < str1.Length;j++)
{
string str2 = Convert.ToString(str[j]);
if (result.Document.ContactName.IndexOf(str2,
StringComparison.CurrentCultureIgnoreCase) != -1)
Note: "ContactName" is string.
Please help with some latest code which improves performance.

You can use linq to check if result.Document.Name contains a word from array.
var str = Convert.ToString(ViewBag.Keyword);
string[] str1 = str.Split(' ');
var names = str1.Where(x => (result.Document.ContactName.Contains(x))).ToList();

You can compare those names are on that string like below,
Remember comparison is case sensitive
var str = Convert.ToString(ViewBag.Keyword);
string[] str1 = str.Split(' ');
if(str1.Any(result.Document.ContactName.Contains)){
//Do Something
}
Example -
var str = "Johnson and Jen";
string[] str1 = str.Split(' ');
string result = "Jendasdbnoahsdasnd"; // I assume your ContactName result is like this
if (str1.Any(result.Contains)) // This gives true because Jen in the string
{
//Do Something
}
But, for the string result = "jendasdbnoahsdasnd" it gives false because of the case.

If you need to check for the exact match of the words you get by splitting the keyword string using a white space against the contact name property from the collection then you can use a regular expression to do that.
The regular expression is of the form \bTheWordGoesHere\b where \b is the word boundary delimiter
Check this sample code snippet.
var keyword = "Johnson and Jen";
var arr = keyword.Split(' ');
var contactName = "Johnson anderson mobile";
for (var i = 0; i < arr.Length; i++)
{
var pattern = string.Format("\\b{0}\\b", arr[i]);
if (Regex.IsMatch(contactName, pattern, RegexOptions.IgnoreCase))
{
// do something
Console.WriteLine("contactName contains the word \"" + arr[i] + "\"");
}
}
rextester link

Below is a sample code for doing the same using clean code
var str = Convert.ToString(ViewBag.Keyword);
var possibleNames = str.split(' ');
//to check if any match exists
bool anyMatch = possibleNames.Any(n => n.Equals(result.Document.ContactName, StringComparison.InvariantCultureIgnoreCase));
//get matched names
var matchedNames = possibleNames.Where(n => n.Equals(result.Document.ContactName, StringComparison.InvariantCultureIgnoreCase));
//do whatever you want with matchedNames now
var array = matchedNames.ToArray();
var list = matchedNames.ToList();

You can split the string "Johnson and Jen" by using another string i.e. " and " this will exactly give you the names which will be appropriate to check against the contact name.
You can check about the Split function here and here
To check whether a property contains a specified string or not you can use the IndexOf method - a simple sample code snippet is given below, you can run this sample code snippet here.
var keyword = "Johnson and Jen";
var arr = keyword.Split(new string[] { " and " }, StringSplitOptions.None);
var contactName = "Johnson";
for (var i = 0; i < arr.Length; i++)
{
if (contactName.IndexOf(arr[i], StringComparison.OrdinalIgnoreCase) >= 0)
{
// do something
Console.WriteLine("contactName contains the string \"" + arr[i] + "\"");
}
}
The code snippet for your scenario would be as follows and in your code you don't need the unnecessary type casting i.e. string str2 = Convert.ToString(str[j]); because str[j] is already a string
var keyword = Convert.ToString(ViewBag.Keyword);
var arr = name.Split(new string[] { " and " }, StringSplitOptions.None);
for (int i = 0; i < arr.Length; i++)
{
if (result.Document.ContactName.IndexOf(arr[i], StringComparison.OrdinalIgnoreCase) != -1)
{
// do something
}
}
Using the StringComparison parameter with its value as StringComparison.OrdinalIgnoreCase will do a case insensitive search

Related

Split string with string and retrieve value c#

I have below string
string arguments = "-p=C:\Users\mplususer\Documents\SharpDevelop Projects\o9\o9\bin\Debug\o9.exe""-t=False""-r=TestRun";
I want to split string with "-t=" and get false value
if (arguments.Contains("-t="))
{
string[] value = arguments.Split(new string[] { "\"-t=" }, StringSplitOptions.None);
if (value.Length != 0)
{
mode = value[1].Replace("\"", "");
}
}
Simply make an IndexOf:
var i = myString.IndexOf("-t=") + 3;
if(i != -1)
value = myString.SubString(i, myString.IndexOf("\"", i) - i);
You can also use a regex for this:
var r = new Regex("-t (true|false)");
var g = r.Match(myString).Groups;
if(g.Count > 1)
value = Convert.ToBoolean(g[1].ToString());
You can do it also like this like your approach without regex:
string arguments = "-p=C:\\Users\\mplususer\\Documents\\SharpDevelop Projects\\o9\\o9\\bin\\Debug\\o9.exe\" \"-t=False\" \"-r=TestRun";
if (arguments.Contains("-t="))
{
string splitted = arguments.Split(new string[] { "\"-t=" }, StringSplitOptions.None)[1];
string value = splitted.Split(new string[] { "\"" }, StringSplitOptions.None)[0];
}
When you split on "-t", you get two fragments. The fragment after that delimiter also contains a "-r" option - which is the issue you are probably seeing.
If you know that the "-t" option is always followed by a "-r", you could simply split on new string[] { "\"-t=", "\"-r=" }. Then you get three fragments and you still want the second one (at index 1).

Showing the intersection between two strings

I am trying to find the intersection between two strings. For example, if string one was my car is bad, and string two was my horse is good, it would return my is.
This is my code:
public static string intersection2(string x1, string x2)
{
string[] string1 = x1.Split(' ');
string[] string2 = x2.Split(' ');
string[] m = string1.Distinct();
string[] n = string2.Distinct();
string Test;
var results = m.Intersect(n,StringComparer.OrdinalIgnoreCase);
Test = results.ToString();
return Test;
}
But I get the error System.Linq.Enumerable+d__921[System.String]`. Could someone explain what's going on, and how I can fix it?
You're not seeing an error - what you are seeing is the fully qualified name of the type of result, which is System.Linq.Enumerable+d_921[System.String]. This is the default behavior for ToString(), unless it is overridden in an inheriting class. See Object.ToString().
To show the results of the intersection, you can use String.Join, like this:
Test = String.Join(" ", results);
Which would produce my is.
Note that your code as posted wouldn't compile:
string[] m = string1.Distinct();
string[] n = string2.Distinct();
The above lines generated a Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<string>' to 'string[]'. Adding .ToArray() is one way to resolve this. Full code below:
public static string intersection2(string x1, string x2)
{
string[] string1 = x1.Split(' ');
string[] string2 = x2.Split(' ');
string[] m = string1.Distinct().ToArray();
string[] n = string2.Distinct().ToArray();
string Test;
var results = m.Intersect(n, StringComparer.OrdinalIgnoreCase);
Test = String.Join(" ", results);
return Test;
}
Your logic is okay, you can make it work by fixing a little bit
public static string intersection2(string x1, string x2)
{
string[] string1 = x1.Split(' ');
string[] string2 = x2.Split(' ');
var m = string1.Distinct();
var n = string2.Distinct();
var results = m.Intersect(n, StringComparer.OrdinalIgnoreCase);
//The result is a list of string, so we just have to concat them
var test = " ";
foreach(var k in results) test += k + " ";
return test;
}
Working fiddle: https://dotnetfiddle.net/joO0d9
That's basically happened because you tired to get the string representation of an IEnumerable<string> and it's completely normal because it returns the default ToString() of object class. So in order to fix that you should somehow make your own string representation, which will be s.t. like this:
string[] string1 = x1.Split(' ');
string[] string2 = x2.Split(' ');
string Test;
var results = string1.Intersect(string2, StringComparer.OrdinalIgnoreCase);
Test = string.Join(" ", results);
also note that there is no need to get Distinct result of your arrays, because Intersect is a set operation and naturally returns the Distict result!
This program gets intersection of 2 strings (assuming duplication is allowed)
public String getIntersection(String s1, String s2) {
String common = "";
for (int i = 0; i < s1.length(); i++) {
for (int j = 0; j < s2.length(); j++) {
if (s1.length() == 0 || s1.length() == 0)
return common;
if (s1.charAt(i) == s2.charAt(j)) {
common = common + s1.charAt(i);
// delete character from each if there is a match
s1 = s1.substring(0, i) + s1.substring(i + 1);
s2 = s2.substring(0, j) + s2.substring(j + 1);
i = -1;
break;
}
}
}
return common;
}

Separating string on each character and putting it in an array

I'm pulling a string from a MySQL database containing all ID's from friends in this format:
5+6+12+33+1+9+
Now, whenever i have to add a friend it's simple, I just take the the string and add whatever ID and a "+". My problem lies with separating all the ID's and putting it in an array. I'm currently using this method
string InputString = "5+6+12+33+1+9+";
string CurrentID = string.Empty;
List<string> AllIDs = new List<string>();
for (int i = 0; i < InputString.Length; i++)
{
if (InputString.Substring(i,1) != "+")
{
CurrentID += InputString.Substring(i, 1);
}
else
{
AllIDs.Add(CurrentID);
CurrentID = string.Empty;
}
}
string[] SeparatedIDs = AllIDs.ToArray();
Even though this does work it just seems overly complicated for what i'm trying to do.
Is there an easier way to split strings or cleaner ?
Try this:-
var result = InputString.Split(new char[] { '+' });
You can use other overloads of Split
as well if you want to remove empty spaces.
You should to use the Split method with StringSplitOptions.RemoveEmptyEntries. RemoveEmptyEntries helps you to avoid empty string as the last array element.
Example:
char[] delimeters = new[] { '+' };
string InputString = "5+6+12+33+1+9+";
string[] SeparatedIDs = InputString.Split(delimeters,
StringSplitOptions.RemoveEmptyEntries);
foreach (string SeparatedID in SeparatedIDs)
Console.WriteLine(SeparatedID);
string[] IDs = InputString.Split('+'); will split your InputString into an array of strings using the + character
var result = InputString.Split('+', StringSplitOptions.RemoveEmptyEntries);
extra options needed since there is a trailing +

Alternatively upper- and lowercase words in a string

I use Visual Studio 2010 ver.
I have array strings [] = { "eat and go"};
I display it with foreach
I wanna convert strings like this : EAT and GO
Here my code:
Console.Write( myString.First().ToString().ToUpper() + String.Join("",myString].Skip(1)).ToLower()+ "\n");
But the output is : Eat and go . :D lol
Could you help me? I would appreciate it. Thanks
While .ToUpper() will convert a string to its upper case equivalent, calling .First() on a string object actually returns the first element of the string (since it's effectively a char[] under the hood). First() is actually exposed as a LINQ extension method and works on any collection type.
As with many string handling functions, there are a number of ways to handle it, and this is my approach. Obviously you'll need to validate value to ensure it's being given a long enough string.
using System.Text;
public string CapitalizeFirstAndLast(string value)
{
string[] words = value.Split(' '); // break into individual words
StringBuilder result = new StringBuilder();
// Add the first word capitalized
result.Append(words[0].ToUpper());
// Add everything else
for (int i = 1; i < words.Length - 1; i++)
result.Append(words[i]);
// Add the last word capitalized
result.Append(words[words.Length - 1].ToUpper());
return result.ToString();
}
If it's always gonna be a 3 words string, the you can simply do it like this:
string[] mystring = {"eat and go", "fast and slow"};
foreach (var s in mystring)
{
string[] toUpperLower = s.Split(' ');
Console.Write(toUpperLower.First().ToUpper() + " " + toUpperLower[1].ToLower() +" " + toUpperLower.Last().ToUpper());
}
If you want to continuously alternate, you can do the following:
private static string alternateCase( string phrase )
{
String[] words = phrase.split(" ");
StringBuilder builder = new StringBuilder();
//create a flag that keeps track of the case change
book upperToggle = true;
//loops through the words
for(into i = 0; i < words.length; i++)
{
if(upperToggle)
//converts to upper if flag is true
words[i] = words[i].ToUpper();
else
//converts to lower if flag is false
words[i] = words[i].ToLower();
upperToggle = !upperToggle;
//adds the words to the string builder
builder.append(words[i]);
}
//returns the new string
return builder.ToString();
}
Quickie using ScriptCS:
scriptcs (ctrl-c to exit)
> var input = "Eat and go";
> var words = input.Split(' ');
> var result = string.Join(" ", words.Select((s, i) => i % 2 == 0 ? s.ToUpperInvariant() : s.ToLowerInvariant()));
> result
"EAT and GO"

How to make a first letter capital in C#

How can the first letter in a text be set to capital?
Example:
it is a text. = It is a text.
public static string ToUpperFirstLetter(this string source)
{
if (string.IsNullOrEmpty(source))
return string.Empty;
// convert to char array of the string
char[] letters = source.ToCharArray();
// upper case the first char
letters[0] = char.ToUpper(letters[0]);
// return the array made of the new char array
return new string(letters);
}
It'll be something like this:
// precondition: before must not be an empty string
String after = before.Substring(0, 1).ToUpper() + before.Substring(1);
polygenelubricants' answer is fine for most cases, but you potentially need to think about cultural issues. Do you want this capitalized in a culture-invariant way, in the current culture, or a specific culture? It can make a big difference in Turkey, for example. So you may want to consider:
CultureInfo culture = ...;
text = char.ToUpper(text[0], culture) + text.Substring(1);
or if you prefer methods on String:
CultureInfo culture = ...;
text = text.Substring(0, 1).ToUpper(culture) + text.Substring(1);
where culture might be CultureInfo.InvariantCulture, or the current culture etc.
For more on this problem, see the Turkey Test.
If you are using C# then try this code:
Microsoft.VisualBasic.StrConv(sourceString, Microsoft.VisualBasic.vbProperCase)
I use this variant:
private string FirstLetterCapital(string str)
{
return Char.ToUpper(str[0]) + str.Remove(0, 1);
}
If you are sure that str variable is valid (never an empty-string or null), try:
str = Char.ToUpper(str[0]) + str[1..];
Unlike the other solutions that use Substring, this one does not do additional string allocations. This example basically concatenates char with ReadOnlySpan<char>.
I realize this is an old post, but I recently had this problem and solved it with the following method.
private string capSentences(string str)
{
string s = "";
if (str[str.Length - 1] == '.')
str = str.Remove(str.Length - 1, 1);
char[] delim = { '.' };
string[] tokens = str.Split(delim);
for (int i = 0; i < tokens.Length; i++)
{
tokens[i] = tokens[i].Trim();
tokens[i] = char.ToUpper(tokens[i][0]) + tokens[i].Substring(1);
s += tokens[i] + ". ";
}
return s;
}
In the sample below clicking on the button executes this simple code outBox.Text = capSentences(inBox.Text.Trim()); which pulls the text from the upper box and puts it in the lower box after the above method runs on it.
Take the first letter out of the word and then extract it to the other string.
strFirstLetter = strWord.Substring(0, 1).ToUpper();
strFullWord = strFirstLetter + strWord.Substring(1);
text = new String(
new [] { char.ToUpper(text.First()) }
.Concat(text.Skip(1))
.ToArray()
);
this functions makes capital the first letter of all words in a string
public static string FormatSentence(string source)
{
var words = source.Split(' ').Select(t => t.ToCharArray()).ToList();
words.ForEach(t =>
{
for (int i = 0; i < t.Length; i++)
{
t[i] = i.Equals(0) ? char.ToUpper(t[i]) : char.ToLower(t[i]);
}
});
return string.Join(" ", words.Select(t => new string(t)));;
}
string str = "it is a text";
// first use the .Trim() method to get rid of all the unnecessary space at the begining and the end for exemple (" This string ".Trim() is gonna output "This string").
str = str.Trim();
char theFirstLetter = str[0]; // this line is to take the first letter of the string at index 0.
theFirstLetter.ToUpper(); // .ToTupper() methode to uppercase the firstletter.
str = theFirstLetter + str.substring(1); // we add the first letter that we uppercased and add the rest of the string by using the str.substring(1) (str.substring(1) to skip the first letter at index 0 and only print the letters from the index 1 to the last index.)
Console.WriteLine(str); // now it should output "It is a text"
static String UppercaseWords(String BadName)
{
String FullName = "";
if (BadName != null)
{
String[] FullBadName = BadName.Split(' ');
foreach (string Name in FullBadName)
{
String SmallName = "";
if (Name.Length > 1)
{
SmallName = char.ToUpper(Name[0]) + Name.Substring(1).ToLower();
}
else
{
SmallName = Name.ToUpper();
}
FullName = FullName + " " + SmallName;
}
}
FullName = FullName.Trim();
FullName = FullName.TrimEnd();
FullName = FullName.TrimStart();
return FullName;
}
string Input = " it is my text";
Input = Input.TrimStart();
//Create a char array
char[] Letters = Input.ToCharArray();
//Make first letter a capital one
string First = char.ToUpper(Letters[0]).ToString();
//Concatenate
string Output = string.Concat(First,Input.Substring(1));
Try this code snippet:
char nm[] = "this is a test";
if(char.IsLower(nm[0])) nm[0] = char.ToUpper(nm[0]);
//print result: This is a test

Categories

Resources