I have an array of strings. I want to compare with the string which I am getting from JSON. Comparision should be like this.
For example:
If Account name in one string is Google and in other it is Google Inc, then since Google is part of the Google Inc company name, It should get matched. Otherwise not.
Code which I have written:
for (int i = 0; i < accountCount; i++)
{
//// account is found in the array
name[i] = account.Entities[i].Attributes["name"].ToString();
if (name[i] == message.Current.org_name)
{
flag = 1;
c.CreateOpportunity(message);
break;
}
}
//// account is not found in the array
if (flag == 0)
{
c.CreateAccount(message);
c.CreateOpportunity(message);
}
Try to use Contains function instead :
for (int i = 0; i < accountCount; i++)
{
//// account is found in the array
name[i] = account.Entities[i].Attributes["name"].ToString();
if (name[i].Contains(message.Current.org_name)
|| message.Current.org_name.Contains(name[i]))
{
flag = 1;
break;
}
}
//// account is not found in the array
if (flag == 0)
c.CreateAccount(message);
c.CreateOpportunity(message);
You can use Contains for a case sensitive search
or IndexOf to speficify more options with comparison criteria
However for the fun of it we can use Any on an array or list
Note : none of the above check for null
Contains
var org = message.Current.org_name;
var found = account.Entities.Any( // does any entity contain org ?
x => x.Attributes["name"] // Get Attribute
.ToString() // Convert it to string if needed
.Contains(org));
if (found)
{
c.CreateAccount(message);
}
c.CreateOpportunity(message);
if you would like a case insensative search you can use String.IndexOf
IndexOf
var found = account.Entities.Any( // does any entity contain org ?
x => x.Attributes["name"] // Get Attribute
.ToString() // Convert it to string if needed
.IndexOf(org, StringComparison.OrdinalIgnoreCase) >= 0);
References
String.Contains -
String.Contains Method (String)
String.IndexOf -
String.IndexOf Method (String, StringComparison)
Coparison type - StringComparison Enumeration
Related
I'm new to programmning and I'm taking a course to learn the basics in c#.
Right now I'm doing a console application that are supposed to work as a blog. In the application the user should be able to write a new post, show written posts and search for written posts. The application is supposed to be a list that contains arrays.
I'm almost finished with the application but I want to make a method for the linear search that searches for the written blogposts but I cant get it to work.
Here's the code for the linear search:
case 3:
Console.Write("Write the title for the post you are searching for: ");
string searchedWord = Console.ReadLine();
bool search = false;
for (int i = 0; i < myBlog.Count; i++)
{
if (searchedWord.ToUpper() == myBlog[i][0].ToUpper())
{
search = true;
Console.WriteLine("\nHe post you are looking for exists in the blog:");
Console.WriteLine("\nTitle: " + myBlog[i][0] +
"\nPost: " + myBlog[i][1] +
"\n\nPress enter to return to the menu...");
}
}
if (search == false)
{
Console.WriteLine("The searched word wasn't found. Press enter to return to the menu...");
}
break;
I made a try creating a method for it but I'm doing wrong, can somebody please tell me how to do it?
static string BlogSearch(List<string[]> myBlog, string searchedWord)
{
for (int i = 0; i < myBlog; i++)
{
if (searchedWord.ToUpper() == myBlog[i][0].ToUpper())
return i;
}
return -1;
}
If you are allowed to use Linq, you can do
using System.Linq;
//....
static string[] BlogSearch(List<string[]> myBlog, string searchedWord)
{
// "give me from myBlog ...
// the first element, that fits the criteria OR
// default if such an element is not in the list"
return myBlog.FirstOrDefault(x => x[0].Contains(searchedWord, StringComparison.OrdinalIgnoreCase));
}
See it in action in a Fiddle
Mind that this returns default(string) (which is null) if the searchedWord is not found.
I guess you are using string[] because your class (pun intended) has not come across the concept of classes, yet. So I won't go into that. Just so much: usually, you would model your blog data into a class with specific properties. And later on, you would probably want to keep the data in a Database instead of memory ... but all that is not really related to the problem at hand.
If you are NOT allowed to use Linq:
static string[] BlogSearch(List<string[]> myBlog, string searchedWord)
{
for( int i = 0; i < myBlog.Count; i++ )
{
if( myBlog[i][0].Contains(searchedWord, StringComparison.OrdinalIgnoreCase))
{
return myBlog[i];
}
}
return null;
}
Which is basically the same as the Linq version just coded out explicitly.
See it in action in a Fiddle.
Usage
// ... case 3: ...
var result = BlogSearch(myBlog, searchedWord);
if( result is null )
{
Console.WriteLine("The searched word wasn't found. Press enter to return to the menu...");
}
else
{
Console.WriteLine("\nThe post you are looking for exists in the blog:");
Console.WriteLine("\nTitle: " + result[0] +
"\nPost: " + result[1] +
"\n\nPress enter to return to the menu...");
}
break;
Some hints for you concerning your code:
// You expect to be returning `string`
// but all return statements return `int`.
// vv What you actually need is `string[]`, though.
static string BlogSearch(List<string[]> myBlog, string searchedWord)
{
// vv that's a `List<T>`, so you need `myBlog.Count` here
for (int i = 0; i < myBlog; i++)
{
// Two caveats:
// 1. _Exact_ match
// 2. `ToUpper` does not always work correctly.
// It is advised to use overloads with `StringComparison` argument
if (searchedWord.ToUpper() == myBlog[i][0].ToUpper())
return i;
}
return -1;
}
I'm new in c# and unity and Wondering how could I write this code to check if two string lengths are equal.
with this code unity system shows this error:
error CS1061: Type char' does not contain a definition forLength' and no extension method Length' of typechar' could be found.
for (int i = 0; i < Answers.Length; i++)
{
if (GetAnswer[i].Length == Answers[i].Length)
{
//Do something
}
}
if (yourString.Length == yourOtherString.Length)
{
//dosomething
}
should check if a string is equals in length to another
The problem with your code is that a string is an array of char so it calculate the length of the char (Which do not exist)
for (int i = 0; i < Answers.Length+1; i++)
{
if (GetAnswer.Length == Answers.Length)
{
//Do something
}
}
You also need to increment the value of the for to get the correct length otherwise the Answers.Length will always be short of 1
How do i see if
string1 contains string2 OR
string2 contains string1 OR
String 3 contains string 1 OR
String 1 contains string 3 OR
String 2 contains string 3 OR
string 3 contains String 2 in single line?
like i want to do
if ( string1.contains(string2) || string2.contains(string1) || string3.contains(string1) string3.contains(string2) || .. and so on.. )
{
}
in single check without or clause.
In reality, i have to do this check multiple times and multiple places. So just wondering if there is a better way.
I have updated my business logic or the reason for this logic. We have 6 Sites and we will get just the page names of the sites. i have to check the site names are similar. The only problem is.. i donot get the site names in any particular pattern. like for eg:
String1 = "/search-results"
string2= "www.foo.com/search-results?Id=1234"
string3 = "search-results"
string4= "/search-results?Id=1234"
and if you look at my values, you will note that if you compare any two strings with OR clause.. they will be true.
Put your strings into an array or a list, then:
bool result = yourStrings
.Where((x, idx) =>
yourStrings.Where((y, index) => idx != index && x.Contains(y))
.Any())
.Any();
Explanation:
This query will take each string, and compare them with others and returns a result that indicates whether any of the strings is contains another string in the collection.
For example consider we have three strings foo, bar and fooBar, the steps would be like the following:
Take "foo" and check if it contains bar or fooBar (false)
Take "bar" and check if it contains foo or fooBar (false)
Take "fooBar" and check if it contains foo or bar (true because of foo)
I wish there is an overload of Any that accepts the index parameter...
Edit: here is also more efficient implementation for larger collections:
public static bool ContainsAny(IList<string> source)
{
int count = source.Count;
for (int i = 0; i < count; i++)
{
for (int j = 0; j < count; j++)
{
if (i != j && source[i].Contains(source[j]))
{
return true;
}
}
}
return false;
}
You can have an helper method and use it :
public static void SomeContainsAnOther(this IEnumerable<string> #this)
{
#this.Any(v=>#this.Count(other=>other.Contains(v)) > 1);
}
And use it :
new string[] {string1,string2,string3,..stringN}.SomeContainsAnOther();
I have an array of strings like {"ABC_DEF_GHIJ", "XYZ_UVW_RST", ...} and want to search if my array contains a string partially matching "ABC_DEF". It should return either index (0) or the string itself ("ABC_DEF_GHIJ").
I tried:
int index = Array.IndexOf(saGroups, "ABC_DEF");
But it returns -1.
You can use extension methods and Lambda expressions to achieve this.
If you need the Index of the first element that contains the substring in the array elements, you can do this...
int index = Array.FindIndex(arrayStrings, s => s.StartsWith(lineVar, StringComparison.OrdinalIgnoreCase)) // Use 'Ordinal' if you want to use the Case Checking.
If you need the element's value that contains the substring, just use the array with the index you just got, like this...
string fullString = arrayStrings[index];
Note: The above code will find the first occurrence of the match. Similary, you
can use Array.FindLastIndex() method if you want the last element in the array
that contains the substring.
You will need to convert the array to a List<string> and then use the ForEach extension method along with Lambda expressions to get each element that contains the substring.
Try this:
string[] strArray = { "ABC_DEF_GHIJ", "XYZ_UVW_RST" };
string SearchThisString = "ABC_DEF";
int strNumber;
int i = 0;
for (strNumber = 0; strNumber < strArray.Length; strNumber++)
{
i = strArray[strNumber].IndexOf(SearchThisString);
if (i >= 0)
break;
}
Console.WriteLine("String number: {0}",strNumber);
You can also use Contains:
string [] arr = {"ABC_DEF_GHIJ", "XYZ_UVW_RST"};
for (int i = 0; i < arr.Length; i++)
if (arr[i].Contains("ABC_DEF"))
return i; // or return arr[i]
Simply loop over your string array and check every element with the IndexOf method if it contains the string you want to search for. If IndexOf returns a value other than -1 the string is found in the current element and you can return its index. If we can not find the string to search for in any element of your array return -1.
static int SearchPartial(string[] strings, string searchFor) {
for(int i=0; i<strings.Length; i++) {
if(strings[i].IndexOf(searchFor) != -1)
return i;
}
return -1;
}
See https://ideone.com/vwOERDfor a demo
I have the following code that is suppose to search an array :
for (int i = 0; i < this.passwordList.Length; i++)
{
string userInput = Convert.ToString(this.passInput);
if(userInput == passwordList[i])
{
MessageBox.Show("FOUND");
foundResult = 1;
break;
}
//MessageBox.Show();
}
and the array has the following results :
public string[] passwordList = {"123456", "145784" , "asasas"};
What am I doing wrong!?!?
The mistake is probably here:
string userInput = Convert.ToString(this.passInput);
If you have a WinForms control, try something like this instead:
string userInput = this.passInput.Text;
You might also want to inspect the value of userInput in a debugger to make sure that it contains the value that you expect.
You havn't provided information about all your variables, but I suspect the the line
string userInput = Convert.ToString(this.passInput);
is the problem. If this.passInput is a control you will get the name of the type of the control and not what the user entered into the control.
If that is true you can simplify your code into something like this:
if (passwordList.Contains(this.passInput.Text)) {
MessageBox.Show("FOUND");
foundResult = 1;
}