在一个单词后拆分字符串

时间:2016-09-14 13:02:32

标签: c# split

我想在字符后面的之后分割一个字符串。 示例字符串:

 A-quick-brown-fox-jumps-over-the-lazy-dog

我想在"jumps-"之后拆分字符串 我可以使用stringname.Split("jumps-")功能吗? 我想要以下输出:

 over-the-lazy-dog. 

4 个答案:

答案 0 :(得分:6)

我建议您使用IndexOfSubstring,因为您实际上需要后缀(“字符串后面的字符串”),而不是拆分:< / p>

  string source = "A-quick-brown-fox-jumps-over-the-lazy-dog";
  string split = "jumps-";

  // over-the-lazy-dog
  string result = source.Substring(source.IndexOf(split) + split.Length);

答案 1 :(得分:0)

    var theString = "A-quick-brown-fox-jumps-over-the-lazy-dog.";
    var afterJumps = theString.Split(new[] { "jumps-" }, StringSplitOptions.None)[1]; //Index 0 would be what is before 'jumps-', index 1 is after.

答案 2 :(得分:0)

您可以扩展Split()方法。事实上,几个月前我就这样做了。可能不是最漂亮的代码,但它完成了工作。此方法在每jumps-分割,而不是在第一个分割。

public static class StringExtensions
{
    public static string[] Split(this String Source, string Separator)
    {
        if (String.IsNullOrEmpty(Source))
            throw new Exception("Source string is null or empty!");
        if (String.IsNullOrEmpty(Separator))
            throw new Exception("Separator string is null or empty!");


        char[] _separator = Separator.ToArray();
        int LastMatch = 0;
        List<string> Result = new List<string>();


        Func<char[], char[], bool> Matches = (source1, source2) =>
        {
            for (int i = 0; i < source1.Length; i++)
            {
                if (source1[i] != source2[i])
                    return false;
            }
            return true;
        };


        for (int i = 0; _separator.Length + i < Source.Length; i++)
        {
            if (Matches(_separator.ToArray(), Source.Substring(i, _separator.Length).ToArray()))
            {
                Result.Add(Source.Substring(LastMatch, i - LastMatch));
                LastMatch = i + _separator.Length;
            }
        }

        Result.Add(Source.Substring(LastMatch, Source.Length - LastMatch));
        return Result.ToArray();
    }
}

答案 3 :(得分:0)

我通常使用扩展方法:

public static string join(this string[] strings, string delimiter) { return string.Join(delimiter, strings); }

public static string[] splitR(this string str, params string[] delimiters) { return str.Split(delimiters, StringSplitOptions.RemoveEmptyEntries); }
//public static string[] splitL(this string str, string delimiter = " ", int limit = -1) { return vb.Strings.Split(str, delimiter, limit); }

public static string before(this string str, string delimiter) { int i = (str ?? "").    IndexOf(delimiter ?? ""); return i < 0 ? str : str.Remove   (i                   ); }  // or return str.splitR(delimiter).First();
public static string after (this string str, string delimiter) { int i = (str ?? "").LastIndexOf(delimiter ?? ""); return i < 0 ? str : str.Substring(i + delimiter.Length); }  // or return str.splitR(delimiter).Last();

样本使用:

stringname.after("jumps-").splitR("-"); // splitR removes empty entries