擷取字串中的子串,擷取字串子串

來源:互聯網
上載者:User

擷取字串中的子串,擷取字串子串

輸入一個連續的字串,輸出一個字串數組,規則是相鄰的字元如果相同,那麼就認為是同一個子串。我的實現如下

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;//*------------------Ctrix Project-------------*//namespace ConsoleApplication1{    /// <summary>    /// main class    /// </summary>    class Program    {        /// <summary>        /// main function        /// Creator:Y        /// Create Date:2014-11-26        /// </summary>        /// <param name="args"></param>        static void Main(string[] args)        {            Console.WriteLine("Please input string:");            string inputString = Console.ReadLine();            string[] array = GetSubStringArray(inputString);            Console.WriteLine("Output string Array:");            foreach (string s in array)            {                Console.WriteLine(s);                            }            Console.Read();        }        /// <summary>        /// input string and get the sub-string array        /// </summary>        /// <param name="s">input string</param>        /// <returns>sub-string array</returns>        public static string[] GetSubStringArray(string s)        {            string[] subStringArray;            if (string.IsNullOrEmpty(s))            {                return null;            }            else if (s.Length == 1)            {                subStringArray = new string[1];                subStringArray[0] = s;                return subStringArray;            }            else            {                int j = 0;                List<string> list = new List<string>();                string temp=string.Empty;                string flag = s.Substring(0,1);                for (int i = 1; i < s.Length; i++)                {                    temp=s.Substring(i,1);                    if (flag != temp)                    {                        list.Add(s.Substring(j,i-j));                        j = i;                        flag=s.Substring(j,1);                    }                }                if (flag != list[list.Count - 1])                {                    list.Add(s.Substring(j));                }                return list.ToArray();              }        }    }}

例如輸入“abbcddefffg”,期待的結果就是一個數組{a,bb,c,dd,e,fff,g}。



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.