hi, i wants to ask some string problems, as below:

string []first
1 2 3 4 5
1 4 5
1 3 4 5

string second="2 3";

double sum=0;
foreach(string a in first)
{
if(     ) // what should i write here?
{
sum++;
}
}

In program above, if string array first contains string second, sum will +1. How should i write the code?

Dani AI

Generated

A simple substring check (what and others pointed to) solves the example you posted, but there are a few real-world issues worth addressing so the check behaves the way you expect.

Use a controlled comparison when you care about case or culture. String.IndexOf accepts a StringComparison so you can do case-insensitive or ordinal comparisons without relying on culture defaults — useful for predictable results across machines. See the docs for String.IndexOf for details: String.IndexOf

For exact token sequences (so "2 3" matches only when 2 and 3 are adjacent tokens, not when 23 or 12 3 appears), split on whitespace and do a sliding comparison of token arrays. That avoids false positives from partial-number matches:

bool ContainsTokenSequence(string haystack, string needle)
{
    if (haystack == null || needle == null) return false;
    var h = haystack.Split(new[]{' ','\t'}, StringSplitOptions.RemoveEmptyEntries);
    var n = needle.Split(new[]{' ','\t'}, StringSplitOptions.RemoveEmptyEntries);
    if (n.Length == 0 || h.Length < n.Length) return false;
    for (int i = 0; i <= h.Length - n.Length; i++)
    {
        bool ok = true;
        for (int j = 0; j < n.Length; j++)
            if (!h[i + j].Equals(n[j], StringComparison.Ordinal)) { ok = false; break; }
        if (ok) return true;
    }
    return false;
}

If you want flexible whitespace (multiple spaces, tabs) or punctuation-aware matching, use a regex. Escape the needle, convert spaces to \s+, and use token boundaries; precompile the regex if you reuse it a lot. See the .NET regex guide: regular expressions

Practical tips: always null-check and normalize input (Trim, remove extra spaces) before matching; pre-split or precompile patterns when checking many strings; prefer StringComparison overloads for predictable, fast matches. Thanks to , and for the initial examples — they cover the quick solution, and the approaches above show safer alternatives for production code.

Recommended Answers

All 6 Replies

Do you mean an exact match( "1 2" == "1 2") or if the array element contains string second as a substring ("1 2" is in "3 1 2 4")?

"the array element contains string second as a substring ("1 2" is in "3 1 2 4")", this what i means..

        string[] first=new string[3];
        int sum = 0;
        first[0] = "1 2 3 4 5";
        first[1] = "1 4 5";
        first[2] = "1 3 4 5";
        string second= "2 3";
        foreach (string a in first)
        {
            if (a.Contains(second))
                sum++;
        }
        Console.WriteLine(sum);
        Console.ReadLine();

Check this example:

string[] array1 = { "12345", "145", "1345" };
            string second= "23";
            int sum = 0;
            foreach (string item in array1)
            {
                if (item.Contains(second))
                    sum++;
            }
            MessageBox.Show("There is/are " + sum + " strings of \"" + second + "\" string in the array.");

problem solved, thanks every1

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.