【问题标题】:Easy way to search a string for strings在字符串中搜索字符串的简单方法
【发布时间】:2009-04-23 18:15:08
【问题描述】:

我正在尝试找到最简单的方法来搜索 string 以查找可能的 strings 数组。我知道对字符执行此操作的简单方法是使用myString.IndexOfAny(charArray)。但是,如果我想在string 中搜索strings 而不仅仅是字符怎么办?是否有任何 .net 技巧或方法可以使这更容易?

基本上,我想做这样的事情:

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

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

我知道有一些方法可以通过循环等来做到这一点。但我希望框架中有一些固有的东西。

【问题讨论】:

  • 我不同意这个副本。似乎他想在数组中的每个字符串中搜索一个子字符串。
  • @Samuel,你从哪里得到的,他显然有 myName 并搜索了一系列“名字”?
  • @TStamper:来自 IndexOfAny(...),除非他对 C# 字符串方法感到非常困惑。
  • 抱歉有任何混淆。我在示例中使用 IndexOfAny 可能具有误导性。我基本上希望有一个“类似”类型的解决方案。

标签: string search c#-2.0


【解决方案1】:

您应该定义是否要查找相等的字符串或搜索匹配的子字符串。在 LINQ 之前和使用 LINQ 时,这两种方法都很容易。

string myName = "rahkim";
string[] names = new string[] { "joe", "bob", "chris" };
相等的字符串,LINQ
bool contains = names.Contains(myName);
相等的字符串,预LINQ
bool contains = new List<string>(name).Contains(myName);
子字符串,LINQ
bool contains = names.Any(name => name.Contains(myName));
子字符串,预 LINQ
bool contains = false;
foreach(string name in names)
  if (name.Contains(myName))
    contains = true;

【讨论】:

  • 感谢这些示例。我实际上很喜欢“相等的字符串,预 LINQ”,但它给了我一个错误 - 参数 '1':无法从 'string[]' 转换为 'string'。我可能在这里遗漏了一些东西......
  • 那是因为它应该是:bool contains = new List&lt;string&gt;(names).Contains(myName); BTW,子字符串,LINQ 也可以更短:bool contains = names.Any(myName.Contains);
【解决方案2】:

如果其他人在尝试搜索像 String.IndexOfAny(String[]) 这样的 .Net 方法时发现了这个问题,这就是我的解决方案:

C#

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 

到

i > first

【讨论】:

  • 在第 6 行,“if (i > 0)” - 应该是“if (i >= 0)”。
【解决方案3】:

您可以(也)使用Array 类的static IndexOf 方法:

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

【讨论】:

    【解决方案4】:

    int IndexOfAny(String[] rgs) 确实不错,但名义上是 O(n^2) 操作。如果在您的应用程序中,字符串集合 rgs 很大并且始终相同,那么最有效的方法是将它们加载到 trie 数据结构中一次,然后重复使用 trie 进行搜索在运行时给出的未知字符串中为它们。

    这里是相关代码,改编自我在网上找到的 C# trie 源代码,归属于“Kerry D. Wong”。在我的版本中,trie 中的每个字符串都有一个泛型类型 TValue 的“有效负载”。要使用这个 trie 来简单地搜索子字符串,可以始终将有效负载设置为 true,如 simple_trie 所示。

    我在此处更改的另一件事是该 trie 自动适应允许存储任意 Unicode 字符串。每个节点上的数组(表征 trie)调整其基数和长度以适应需要存储在该节点上的 Unicode 字符范围。例如,这允许区分大小写的匹配。

    C# 3.0 初始化语法对于这个 trie 很方便,但启用它需要 IEnumerable 的虚拟实现才能编译。 CLR 似乎没有调用 GetEnumerator(),我建议您也不要尝试使用其结果进行枚举。

    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++;
            }
        }
    };
    

    【讨论】:

    • 似乎使用正则表达式和 String.Join("|", args) 作为表达式可能更容易、更有效。
    • @user1664043 RegExs 是一种简单的方法,但由此产生的复杂性有时并不明显或不透明。正如我的帖子第一行所暗示的那样,如果性能至关重要,我的解决方案可能更合适,因为它为时间复杂度提供了透明的保证。
    • 准确地说,IndexOfAny(String[]) 并不是真正的 O(n^2) 而是更像 O(n*m),带有 n 是发生搜索的字符串的大小,m 是正在搜索的字符串的(最大)长度,假设字符串的数量与两者相比都很小n 和 m.
    【解决方案5】:

    下面是正确的语法:

    if(names.Contains(myName))
    {
          //success code//
    }
    

    【讨论】:

    • 我认为 OP 想要进行子字符串匹配.. 或者不是吗?
    • 我没有选择“包含”。当智能感知弹出时,我只得到数组方法。
    • 包含 Linq 以获取扩展 - 请参阅重复问题
    • 我没有 Linq 扩展。还有其他方法吗?
    【解决方案6】:
    if (names.Contains(myName)) 
    {
    //success code//
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-30
      • 2012-01-29
      • 1970-01-01
      • 1970-01-01
      • 2012-05-24
      相关资源
      最近更新 更多