is there a elegant way to parse a word and add spaces before capital letters

后端 未结 7 760
遥遥无期
遥遥无期 2020-12-01 09:43

i need to parse some data and i want to convert

AutomaticTrackingSystem

to

Automatic Tracking System

esse

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 09:54

    Try this:

    using System;
    using System.Linq;
    using System.Text.RegularExpressions;
    
    class MainClass
    {
        public static void Main (string[] args)
        {
            var rx = new Regex
                    (@"([a-z]+[A-Z]|[A-Z][A-Z]+|[A-Z]|[^A-Za-z][^A-Za-z]+)");
    
            string[] tests = {
            "AutomaticTrackingSystem",
            "XMLEditor",
            "AnXMLAndXSLT2.0Tool",
            "NumberOfABCDThings",
            "AGoodMan",
            "CodeOfAGoodMan"
            };
    
            foreach(string t in tests)
            {
                string y = Reverse(t);
                string x = Reverse( rx.Replace(y, @" $1") );
                Console.WriteLine("\n\n{0} -- {1}",y,x);    
            }
    
        }
    
        static string Reverse(string s)
        {
            var ca = s.ToCharArray();
            Array.Reverse(ca);
            string t = new string(ca);
            return t;
        }
    
    }
    

    Output:

    metsySgnikcarTcitamotuA -- Automatic Tracking System 
    
    
    rotidELMX -- XML Editor 
    
    
    looT0.2TLSXdnALMXnA -- An XML And XSLT 2.0 Tool 
    
    
    sgnihTDCBAfOrebmuN -- Number Of ABCD Things 
    
    
    naMdooGA -- A Good Man 
    
    
    naMdooGAfOedoC -- Code Of A Good Man 
    

    It works by scanning the string backward, and making the capital letter the terminator. Wishing there's a parameter for RegEx for scanning the string backwards, so the above separate string reversal won't be needed anymore :-)

提交回复
热议问题