1. 程式人生 > >轉:c#中indexof與substring的區別

轉:c#中indexof與substring的區別

"abcdefg".substring(4,2)
返回的值為:ef
從字串"abcdefg"中第4位開始取,取到第2位。

"abcdefg".substring(4)
返回:efg
從字串"abcdefg"中第4位開始取,取到字串的尾部

Code
//處理連結 add by fengyan 2008-08-19
function handerATag(html)
{
    html2 = html.toLowerCase();
    var result = "";
    var temp7 = "";
    if(html.indexOf("<a") == -1)
    {
        return html2;
    }
   
    while(html2.indexOf("<a")!=-1)
    {
        var temp = html2.substring(0,html2.indexOf("<a")+2);
        var temp2 =  html2.substring(html2.indexOf("<a")+2);
        var temp3 = temp + temp2.substring(0,temp2.indexOf(">")+1);//...<a >結束
        var temp4 = html2.substring(html2.indexOf(temp3)+temp3.length);//<a>之後
        var temp5 = temp4.substring(0,temp4.indexOf("</a>"));//<a>之間</a>
        temp7 = temp4.substring(temp4.indexOf("</a>")+4);//</a>之後
        var temp6 = "";
        var brk = false;
        for(var i = 0 ; i < temp5.length;i++)
        {   
            if(temp5.charAt(i)=='<')
            {
                brk = true;
            }   
            if(temp5.charAt(i)=='>')
            {
                brk = false;
            }
            if(brk)
            {
                temp6 += temp5.charAt(i);
                continue;
            }
       
            temp6 += temp5.charAt(i)+"<!---->";
        }
        result += temp3 + temp6+"</a>";
        html2 = temp7;//控制繼續判斷迴圈
    }
    return result+temp7;
}
 

5月以來,多家<A href="http://www.baidu.com"><FONT color=#ee3d11>基金</FONT></A>公司...

temp=5月以來,多家<A
temp2= href="http://www.baidu.com"><FONT color=#ee3d11>基金</FONT></A>公司...
temp3=5月以來,多家<A href="http://www.baidu.com">
temp4=<FONT color=#ee3d11>基金</FONT></A>公司...
temp5=<FONT color=#ee3d11>基金</FONT>
temp7=公司...

temp6=<FONT color=#ee3d11>基<!---->金</FONT>
result=5月以來,多家<A href="http://www.baidu.com"><FONT color=#ee3d11>基<!---->金</FONT></a>
result+temp7=5月以來,多家<A href="http://www.baidu.com"><FONT color=#ee3d11>基<!---->金</FONT></a>公司...

indexof() :在字串中從前向後定位字元和字串;所有的返回值都是指在字串的絕對位置,如為空則為- 1

string test="asdfjsdfjgkfasdsfsgfhgjgfjgdddd";

test.indexof('d')      =2           //從前向後 定位 d 第一次出現的位置
test.indexof('d',1)    =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))=9

lastindexofany 同上。