在单词后拆分字符串

本文关键字:字符串 拆分 单词 | 更新日期: 2023-09-27 18:06:54

我想在单词后拆分string,而不是在字符后拆分。示例字符串:

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

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

 over-the-lazy-dog. 

在单词后拆分字符串

我建议使用IndexOfSubstring,因为您实际上想要后缀("单词后的字符串"(,而不是拆分

  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);
    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.

我通常使用扩展方法:

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

您可以扩展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();
    }
}