查找字符串共同preFIX [英] Find common prefix of strings

查看:144
本文介绍了查找字符串共同preFIX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有4个字符串:

 H:/ A / B / C
H:/ A / B / D
H:/ A / B / E
H:/ A / C

我想找到那些字符串共同preFIX,即H:/ A
如何找到的?

通常我会分裂与分隔字符串/键,把它放在另一个列表,等等。结果
有没有更好的办法呢?


解决方案

 的String [] XS =新[] {H:/ A / B / C,H:/ A / b / D,H:/ A / b / E,H:/ A / C};字符串x =的string.join(/,xs.Select(S = GT; s.Split('/')AsEnumerable())。
                              .Transpose()
                              .TakeWhile(S => s.All(D = D 1和D == s.First()))
                              。选择(S => s.First()));

 公共静态的IEnumerable<&IEnumerable的LT; T>>移调< T>(
    这IEnumerable的<&IEnumerable的LT; T>>资源)
{
    VAR枚举= source.Select(E => e.GetEnumerator())ToArray的()。
    尝试
    {
        而(enumerators.All(E => e.MoveNext()))
        {
            产量返回enumerators.Select(E => e.Current).ToArray();
        }
    }
    最后
    {
        Array.ForEach(统计员,E => e.Dispose());
    }
}

I am having 4 strings:

"h:/a/b/c"
"h:/a/b/d"
"h:/a/b/e"
"h:/a/c"

I want to find the common prefix for those strings, i.e. "h:/a". How to find that?

Usually I'd split the string with delimiter '/' and put it in another list, and so on.
Is there any better way to do it?

解决方案

string[] xs = new[] { "h:/a/b/c", "h:/a/b/d", "h:/a/b/e", "h:/a/c" };

string x = string.Join("/", xs.Select(s => s.Split('/').AsEnumerable())
                              .Transpose()
                              .TakeWhile(s => s.All(d => d == s.First()))
                              .Select(s => s.First()));

with

public static IEnumerable<IEnumerable<T>> Transpose<T>(
    this IEnumerable<IEnumerable<T>> source)
{
    var enumerators = source.Select(e => e.GetEnumerator()).ToArray();
    try
    {
        while (enumerators.All(e => e.MoveNext()))
        {
            yield return enumerators.Select(e => e.Current).ToArray();
        }
    }
    finally
    {
        Array.ForEach(enumerators, e => e.Dispose());
    }
}

这篇关于查找字符串共同preFIX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆