2016-09-14 165 views
1

我想在字符後分割一個字符串,不是後面的字符。 例字符串:將字符串拆分後一個字

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

我想以後"jumps-" 我可以使用stringname.Split("jumps-")函數將字符串分割? 我想下面的輸出:

over-the-lazy-dog. 
+1

你忘了說字符串名稱是什麼。 – Jacobr365

回答

1
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. 
5

我建議使用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); 
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(); 
    } 
} 
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