Does C# have a String Tokenizer like Java's?

前端 未结 11 1514
日久生厌
日久生厌 2020-12-01 11:31

I\'m doing simple string input parsing and I am in need of a string tokenizer. I am new to C# but have programmed Java, and it seems natural that C# should have a string tok

11条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 12:23

    If you're trying to do something like splitting command line arguments in a .NET Console app, you're going to have issues because .NET is either broken or is trying to be clever (which means it's as good as broken). I needed to be able to split arguments by the space character, preserving any literals that were quoted so they didn't get split in the middle. This is the code I wrote to do the job:

    private static List Tokenise(string value, char seperator)
    {
        List result = new List();
        value = value.Replace("  ", " ").Replace("  ", " ").Trim();
        StringBuilder sb = new StringBuilder();
        bool insideQuote = false;
        foreach(char c in value.ToCharArray())
        {
            if(c == '"')
            {
                insideQuote = !insideQuote;
            }
            if((c == seperator) && !insideQuote)
            {
                if (sb.ToString().Trim().Length > 0)
                {
                    result.Add(sb.ToString().Trim());
                    sb.Clear();
                }
            }
            else
            {
                sb.Append(c);
            }
        }
        if (sb.ToString().Trim().Length > 0)
        {
            result.Add(sb.ToString().Trim());
        }
    
        return result;
    }
    

提交回复
热议问题