Easy way to find strings for strings

I am trying to find the easiest way to search stringfor an array of possible strings. I know that an easy way to do this for characters is to use myString.IndexOfAny(charArray). But what if I wanted to search for my stringfor string, not just the characters? Are there any .net tricks or methods to facilitate this?

Basically, I would like to do something like this:

string myName = "rahkim";
string[] names = new string[] {"joe","bob","chris"};

if(myName.IndexOfAny(names) >= 0)
{
      //success code//
}

I know there are ways to do this with loops, etc. But I was hoping for something inherent in infrastructure.

+3
source share
6 answers

You can (also) use the static IndexOfclass method Array:

bool hasName = Array.IndexOf(names, myName) > -1;
+3
source

, . - pre-LINQ LINQ.

string myName = "rahkim";
string[] names = new string[] { "joe", "bob", "chris" };
, LINQ
bool contains = names.Contains(myName);
, Pre-LINQ
bool contains = new List<string>(name).Contains(myName);
, LINQ
bool contains = names.Any(name => name.Contains(myName));
, Pre-LINQ
bool contains = false;
foreach(string name in names)
  if (name.Contains(myName))
    contains = true;
+10

- .Net-, String.IndexOfAny(String []), :

#

public int IndexOfAny(string test, string[] values)
{
int first = -1;
foreach (string item in values) {
    int i = test.IndexOf(item);
    if (i >= 0) {
        if (first > 0) {
            if (i < first) {
                first = i;
            }
        } else {
            first = i;
        }
    }
}
return first;
}

VB

Public Function IndexOfAny(test As String, values As String()) As Integer
        Dim first As Integer = -1
        For Each item As String In values
            Dim i As Integer = test.IndexOf(item)
            If i >= 0 Then
                If first > 0 Then
                    If i < first Then
                        first = i
                    End If
                Else
                    first = i
                End If
            End If
        Next
        Return first
    End Function

LastIndexOfAny (String []),

i < first 

to

i > first
+6

int IndexOfAny (String [] rgs) , O (n ^ 2). rgs , , trie , trie , .

, # trie, , " . ". trie " " TValue. trie , ​​ true, simple_trie.

, , , trie Unicode. node, trie-adjusts , Unicode, node. , , .

The C # 3.0 initialization syntax is convenient for this trie, but its inclusion requires a dummy IEnumerable implementation to compile. The CLR does not seem to call GetEnumerator (), and I suggest you not try to list its result as well.

using System;
using System.Collections.Generic;
using System.Linq;  // only used in Main()

class Program
{
    // trie with payload of type <String>
    static Trie<String> value_trie = new Trie<String>
    {
        { "rabbit", "cute" },
        { "giraffe", "tall" },
        { "ape", "smart" },
        { "hippo", "large" },
    };

    // degenerate case of a trie without payload
    static Trie<bool> simple_trie = new Trie<bool>
    {
        { "rabbit", true },
        { "giraffe", true },
        { "ape", true },
        { "hippo", true },
    };

    static void Main(String[] args)
    {
        String s = "Once upon a time, a rabbit met an ape in the woods.";

        // Retrieve payloads for words in the string.
        //
        // output:
        //      cute
        //      smart
        foreach (String word in value_trie.AllSubstringValues(s))
            Console.WriteLine(word);

        // Simply test a string for any of the words in the trie.
        // Note that the Any() operator ensures that the input is no longer
        // traversed once a single result is found.
        //
        // output:
        //      True
        Console.WriteLine(simple_trie.AllSubstringValues(s).Any(e=>e));

        s = "Four score and seven years ago.";
        // output:
        //      False
        Console.WriteLine(simple_trie.AllSubstringValues(s).Any(e => e));
    }
}

class TrieNode<TValue>
{
    private TrieNode<TValue>[] nodes = null;
    private TValue m_value = default(TValue);
    private Char m_base;

    public Char Base { get { return m_base; } }
    public bool IsEnd { get { return !m_value.Equals(default(TValue)); } }

    public TValue Value
    {
        get { return m_value; }
        set { m_value = value; }
    }

    public IEnumerable<TrieNode<TValue>> Nodes { get { return nodes; } }

    public TrieNode<TValue> this[char c]
    {
        get
        {
            if (nodes != null && m_base <= c && c < m_base + nodes.Length)
                return nodes[c - m_base];
            return null;
        }
    }

    public TrieNode<TValue> AddChild(char c)
    {
        if (nodes == null)
        {
            m_base = c;
            nodes = new TrieNode<TValue>[1];
        }
        else if (c >= m_base + nodes.Length)
        {
            Array.Resize(ref nodes, c - m_base + 1);
        }
        else if (c < m_base)
        {
            Char c_new = (Char)(m_base - c);
            TrieNode<TValue>[] tmp = new TrieNode<TValue>[nodes.Length + c_new];
            nodes.CopyTo(tmp, c_new);
            m_base = c;
            nodes = tmp;
        }

        TrieNode<TValue> node = nodes[c - m_base];
        if (node == null)
        {
            node = new TrieNode<TValue>();
            nodes[c - m_base] = node;
        }
        return node;
    }
};

class Trie<TValue> : System.Collections.IEnumerable
{
    private TrieNode<TValue> _root = new TrieNode<TValue>();

    // This dummy enables C# 3.0 initialization syntax
    public System.Collections.IEnumerator GetEnumerator()
    {
        return null;
    }

    public void Add(String s, TValue v)
    {
        TrieNode<TValue> node = _root;
        foreach (Char c in s)
            node = node.AddChild(c);

        node.Value = v;
    }

    public bool Contains(String s)
    {
        TrieNode<TValue> node = _root;
        foreach (Char c in s)
        {
            node = node[c];
            if (node == null)
                return false;
        }
        return node.IsEnd;
    }

    public TValue Find(String s_in)
    {
        TrieNode<TValue> node = _root;
        foreach (Char c in s_in)
        {
            node = node[c];
            if (node == null)
                return default(TValue);
        }
        return node.Value;
    }

    public IEnumerable<TValue> FindAll(String s_in)
    {
        TrieNode<TValue> node = _root;
        foreach (Char c in s_in)
        {
            node = node[c];
            if (node == null)
                break;
            if (node.Value != null)
                yield return node.Value;
        }
    }

    public IEnumerable<TValue> AllSubstringValues(String s)
    {
        int i_cur = 0;
        while (i_cur < s.Length)
        {
            TrieNode<TValue> node = _root;
            int i = i_cur;
            while (i < s.Length)
            {
                node = node[s[i]];
                if (node == null)
                    break;
                if (node.Value != null)
                    yield return node.Value;
                i++;
            }
            i_cur++;
        }
    }
};
+3
source

Here is the correct syntax:

if(names.Contains(myName))
{
      //success code//
}
+2
source
if (names.Contains(myName)) 
{
//success code//
}
+1
source

Source: https://habr.com/ru/post/1706984/


All Articles