在C#中如何用代码实现查找和替换字符、字符串的功能,请尽量详细点,谢谢!

解决方案 »

  1.   

    Replace方法可以替换掉一个字符串中的某些特定字符或者子串。  语法:  public string Replace (string oldValue,string newValue)  参数:  oldValue:要替换的字符。  newValue:要替换oldValue的所有匹配项的字符。  本例通过String类的Replace方法将字符串“soAsp.net”替换成字符串“www.soAsp.net”。  代码如下:    protected void Button1_Click(object sender, EventArgs e)    {        string str1 = Label1.Text.ToString();        string str2=Label2.Text.ToString();        //使用Replace方法替换字符串       string str = str1.Replace(str1, str2);        Page.RegisterStartupScript("","<script>alert('原始字符被替换为:"+str+"')</script>");    } 
      

  2.   

    IndexOf()
    查找字串中指定字符或字串首次出现的位置,返首索引值,如:
    str1.IndexOf("字"); //查找“字”在str1中的索引值(位置)
    str1.IndexOf("字串");//查找“字串”的第一个字符在str1中的索引值(位置)
    str1.IndexOf("字",start,end);//从str1第start+1个字符起,查找end个字符,查找“字”在字符串STR1中的位置[从第一个字符算起]注意:start+end不能大于str1的长度indexof参数为string,在字符串中寻找参数字符串第一次出现的位置并返回该位置。如string s="0123dfdfdf";int i=s.indexof("df");这时i==4。
    如果需要更强大的字符串解析功能应该用Regex类,使用正则表达式对字符串进行匹配。
    indexof() :在字符串中从前向后定位字符和字符串;所有的返回值都是指在字符串的绝对位置,如为空则为- 1string test="asdfjsdfjgkfasdsfsgfhgjgfjgdddd";   test.indexof(’d’)         =2          //从前向后 定位 d 第一次出现的位置
       test.indexof(’d’,5,2)   =6         //从前向后 定位 d 从第5 位开始查,查2位,即 从第5位到第7位;lastindexof() :在字符串中从后向前定位字符和字符串;
    用法和 indexof() 完全相同。
    下面介绍   IndexOfAny ||lastindexofany他们接受字符数组做为变元,其他方法同上,返回数组中任何一个字符最早出现的下标位置如下         char[] bbv={’s’,’c’,’b’};
             string abc = "acsdfgdfgchacscdsad";
            
             Response.Write(abc.IndexOfAny(bbv))=1
             Response.Write(abc.IndexOfAny(bbv, 5))=9
             Response.Write(abc.IndexOfAny(bbv, 5, 3))=9lastindexofany 同上。
    ====================================================================
    substring() 用法string a="aadsfdjkfgklfdglfd"a.substring(5)      //截取从第五位以后的所有字符串a.substring(0,5)     //截取从第0到第5 以后的所有字符串
      

  3.   


    Console.WriteLine(new DataTable().Compute("1*1/2*1/3*1/4*1/5",null));   //0.00833333333333333