[C#] 字串處理

  • 542
  • 0
  • 2015-07-17

摘要:[C#] 字串處理


using System;
using System.Windows.Forms;

namespace Calc
{
    public partial class frmString : Form
    {
        public frmString()
        {
            InitializeComponent();
        }

        private void frmString_Load(object sender, EventArgs e)
        {
            
            //Length, IndexOf, LastIndexOf
            string s1 = " A,b,C,d,E,f,G,h,I ";
            string s2 = ",";
            int i1 = s1.Length; //19
            int i2 = s1.IndexOf(s2); //2
            int i3 = s1.LastIndexOf(s2); //16
                      
            //IndexOfAny, LastIndexOfAny
            string s1 = "1+2-3*4/5";
            char[] c1 = { '+', '-', '*', '/' };
            int i1 = s1.IndexOfAny(c1); //1
            int i2 = s1.LastIndexOfAny(c1); //7
                      
            //ToUpper, ToLower, Trim
            string s1 = " A,b,C,d,E,f,G,h,I ";
            string s2 = s1.ToUpper(); // A,B,C,D,E,F,G,H,I 
            string s3 = s1.ToLower(); // a,b,c,d,e,f,g,h,i 
            string s4 = s1.Trim(); //A,b,C,d,E,f,G,h,I
                       
            //PadLeft
            string s1 = "123456789";
            char c1 = '0';
            string s2 = s1.PadLeft(s1.Length + 1, c1); //0123456789
                       
            //CompareTo, Contains, Equals
            string s1 = "a";
            string s2 = "b";
            int i1 = s1.CompareTo(s2); //-1:s1s2
            bool b1 = s1.Contains(s2); //false
            bool b2 = s1.Equals(s2); //false
                                
            //Replace, Split, Join, Concat
            string s1 = "1+2-3*4/5";
            string s2 = s1.Replace("+", ",+,").Replace("-", ",-,").Replace("*", ",*,").Replace("/", ",/,"); //1,+,2,-,3,*,4,/,5
            string[] a1 = s2.Split(','); //{1,+,2,-,3,*,4,/,5}          
            string s3 = string.Join(",", a1); //1,+,2,-,3,*,4,/,5
            string s4 = string.Concat(a1); //1+2-3*4/5
                       
            //Insert, Remove, Substring
            string s1 = "y=2x+1";
            string s2 = s1.Insert(s1.IndexOf('='), "+"); //y+=2x+1
            string s3 = s1.Remove(s1.IndexOf('x')); //y=2
            string s4 = s1.Substring(s1.IndexOf('x')); //x+1
            
        }
    }
}