39

I need to split a string let's say "asdf aA asdfget aa uoiu AA" split using "aa" ignoring the case. to

"asdf "
"asdfget "
"uoiu "
1
  • Plus1 for not using real words but still maintaining continuity of the question
    – JKennedy
    Nov 30, 2015 at 11:02

10 Answers 10

86

There's no easy way to accomplish this using string.Split. (Well, except for specifying all the permutations of the split string for each char lower/upper case in an array - not very elegant I think you'll agree.)

However, Regex.Split should do the job quite nicely.

Example:

var parts = Regex.Split(input, "aa", RegexOptions.IgnoreCase);
3
  • 1
    No problem. And yeah, it's one of those little hidden gems in the framework.
    – Noldorin
    Sep 17, 2009 at 0:06
  • Visual Basic does this so easily (with Strings.Split)... Am I actually going to regret switching to C#?
    – beppe9000
    Mar 5, 2018 at 0:29
  • 1
    FYI: in C#, Regex.Split consumes the delimiter. stringVar.Split does not Sep 15, 2020 at 11:26
9

If you don't care about case, then the simplest thing to do is force the string to all uppercase or lowercase before using split.

stringbits = datastring.ToLower().Split("aa")

If you care about case for the interesting bits of the string but not the separators then I would use String.Replace to force all the separators to a specific case (upper or lower, doesn't matter) and then call String.Split using the matching case for the separator.

strinbits = datastring.Replace("aA", "aa").Replace("AA", "aa").Split("aa")
6

In your algorithm, you can use the String.IndexOf method and pass in OrdinalIgnoreCase as the StringComparison parameter.

1
  • 1
    So there is no way to take advantage of String.Split?
    – jdelator
    Sep 16, 2009 at 23:56
4

My answer isn't as good as Noldorin's, but I'll leave it so people can see the alternative method. This isn't as good for simple splits, but it is more flexible if you need to do more complex parsing.

using System.Text.RegularExpressions;

string data = "asdf aA asdfget aa uoiu AA";
string aaRegex = "(.+?)[aA]{2}";

MatchCollection mc = Regex.Matches(data, aaRegex);

foreach(Match m in mc)
{
    Console.WriteLine(m.Value);
}
3

Use My Method to Split

public static string[] Split(this string s,string word,StringComparison stringComparison)
    {
        List<string> tmp = new List<string>();
        int wordSt;
        s.IndexOf(word, 0, stringComparison);
        while(s.IndexOf(word, 0, stringComparison) > -1)
        {
            wordSt = s.IndexOf(word, 0, stringComparison);
            tmp.Add(s.Substring(0, wordSt));
            s = s.Substring(wordSt + word.Length);
        }
        tmp.Add(s);
        return tmp.ToArray();
    }
1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Nov 12, 2021 at 6:58
2

It's not the pretties version but also works:

"asdf aA asdfget aa uoiu AA".Split(new[] { "aa", "AA", "aA", "Aa" }, StringSplitOptions.RemoveEmptyEntries);
1
  • Yeah, this is what I meant by permutations - it becomes quite cumbersome for longer split strings.
    – Noldorin
    Sep 17, 2009 at 0:10
1
    public static List<string> _Split(this string input,string[] splt)
    {
        List<string> _Result=new List<string>();
        foreach(string _splt in splt)
        {
            if (splt.Count() == 1)
            { 
                _Result.AddRange(Regex.Split(input, _splt, RegexOptions.IgnoreCase).ToList());
            }
            else 
            {
                List<string> NewStr = Regex.Split(input, _splt, RegexOptions.IgnoreCase).ToList();
                foreach(string _NewStr in NewStr)
                {
                    List<string> NewSplt = splt.ToList();
                    NewSplt.Remove(_splt);
                    return _Split(_NewStr, NewSplt.ToArray());
                }
            } 
        }
        return _Result;
    } 

then use this function as bellow

public frmThematicConversation()
{
    InitializeComponent();
    string str = "a b c d e f g h a b c f a d c b f";
    string[] splt = { "a", "b" };
    List<string> _result = str._Split(splt);
}
0
1

Building on the answer from @Noldorin i made this extension method.

It takes in more than one seperator string, and mimics the behavior of string.Split(..) if you supply several seperator strings. It has invariant ('culture-unspecific') culture and ignores cases of course.

/// <summary>
/// <see cref="string.Split(char[])"/> has no option to ignore casing.
/// This functions mimics <see cref="string.Split(char[])"/> but also ignores casing.
/// When called with <see cref="StringSplitOptions.RemoveEmptyEntries"/> <see cref="string.IsNullOrWhiteSpace(string)"/> is used to filter 'empty' entries.
/// </summary>
/// <param name="input">String to split</param>
/// <param name="separators">Array of separators</param>
/// <param name="options">Additional options</param>
/// <returns></returns>
public static IEnumerable<string> SplitInvariantIgnoreCase(this string input, string[] separators, StringSplitOptions options)
{
    if (separators == null) throw new ArgumentNullException(nameof(separators));
    if (separators.Length <= 0) throw new ArgumentException("Value cannot be an empty collection.", nameof(separators));
    if (string.IsNullOrWhiteSpace(input)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(input));

    // Build a regex pattern of all the separators this looks like aa|bb|cc
    // The Pipe character '|' means alternative.
    var regexPattern = string.Join("|", separators);

    var regexSplitResult = Regex.Split(input, regexPattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);

    // NOTE To be honest - i don't know the exact behaviour of Regex.Split when it comes to empty entries.
    //      Therefore i doubt that filtering null values even matters - however for consistency i decided to code it in anyways.
    return options.HasFlag(StringSplitOptions.RemoveEmptyEntries) ? 
        regexSplitResult.Where(c => !string.IsNullOrWhiteSpace(c)) 
        : regexSplitResult;
}
1

I have had good success with this extension method I wrote that uses .replace() to find and fix the casing.

You call it as follows:

var result = source.Split(prefix, StringComparison.InvariantCultureIgnoreCase);

The extension method is defined as follows.

public static string[] Split(this string source, string separator, 
    StringComparison comparison = StringComparison.CurrentCulture, 
    StringSplitOptions splitOptions = StringSplitOptions.None)
{
    if (source is null || separator is null)
        return null;

    // Pass-through the default case.
    if (comparison == StringComparison.CurrentCulture)
        return source.Split(new string[] { separator }, splitOptions);
    
    // Use Replace to deal with the non-default comparison options.
    return source
        .Replace(separator, separator, comparison)
        .Split(new string[] { separator }, splitOptions);
}

NOTE: This method deals with my default case where I am usually passing a single string separator.

0
Dim arr As String() = Strings.Split("asdf aA asdfget aa uoiu AA", 
                                    "aa" ,, CompareMethod.Text)

CompareMethod.Text ignores case.

1
  • 1
    note for further readers; this is VB specific and not for C# (AFAIK)
    – sommmen
    Sep 1, 2020 at 9:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.