Reputation: 198
I want to split a string
after a word, not after the character.
Example string:
A-quick-brown-fox-jumps-over-the-lazy-dog
I want to split the string after "jumps-"
can I use the stringname.Split("jumps-")
function?
I want the following output:
over-the-lazy-dog.
Upvotes: 3
Views: 15108
Reputation: 787
You could extend the Split() method. In fact, I did this a few months ago. Probably not the prettiest code but it gets the job done. This method splits at every jumps-
, not just at the first one.
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();
}
}
Upvotes: 0
Reputation: 22866
I usually use extension methods:
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();
sample use:
stringname.after("jumps-").splitR("-"); // splitR removes empty entries
Upvotes: 0
Reputation: 186668
I suggest using IndexOf
and Substring
since you actually want a suffix ("String after word"), not a split:
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);
Upvotes: 13
Reputation: 2950
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.
Upvotes: 1