C# 字串常用操作

來源:互聯網
上載者:User

標籤:c#   字串處理   

            string str1 = "C#操作字串<幾種常見方式>如下";

            string str2 = "C#操作字串";


           //比較字串 Compare,Equal
            //1,compare,int 1
            string.Compare(str1, str2);
            str1.CompareTo(str2);
            //2,equal,bool true
            string.Equals(str1, str2);
            str1.Equals(str2);
            //格式化字串
            string.Format("{0},{1} !!!", str1, str2);


            //Format可以格式化日期
            DateTime dt = DateTime.Now;
            string time = string.Format("{0:D}", dt);
            /* dt 2014-08-22 14:37:05
            D 2014年8月22
            d 2014-08-21
            T 14:37:05
            t 14:37
            F 2014年8月22 14:37:05
            f 2014年8月22 14:37
            M/m 08月22日
            Y/y 2014年8月
            */


            //截取字串 從1開始截取5個字元  Substring
            string str3 = str1.Substring(1, 5);


            //分割字串 
            char[] separator = { "<", ">" };
            string[] splitstrings = new string[100];
            splitstrings = str1.Split(separator);
            for (int i = 0; i < splitstrings.Length; i++) {
                MessageBox.Show("項{0}:{1}\r\n",i,splitstrings[i]);
                /*
                 結果:
                  項0:C#操作字串
                  項1:幾種常見方式
                  項2:如下
                 */
            }


            //插入填充字串 Insert,PadLeft/PadRight
            //1,   0表示開始位置
            string str4 = str1.Insert(0, "插入的資料");
            //2,   左右填充字串
            string sr1 = "*^_^*";
            string sr2 = sr1.PadLeft(6, ‘(‘);
            string sr3 = sr2.PadRight(7, ‘)‘);//6和7表示填充後的總字元個數
            //sr3  (*^_^*)


            //刪除字串 Remove
            string str5 = str1.Remove(5);//移除5以後的所有字元
            string str6 = str1.Remove(5, 2);//從5開始移除2個字元


            //複製 Copy/CopyTo
            string str7 = string.Copy(str1);
            //將字串str1從索引2開始的4個字元複製到字元數組mychar中
            char[] mychar = new char[100];
            str1.CopyTo(2, mychar, 0, 4);


            //替換字串  a,b 可以是一個或多個字元   Replace
            string str8=str1.Replace(‘a‘,‘b‘);

C# 字串常用操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.