当前位置导航:炫浪网>>网络学院>>编程开发>>Visual C#教程

C#字符串测试:字符串截取,字符串分割

1 字符串分割

string url = "http://asdfsfd
  • asdf
  • asdfsdf
  • ";
    string[] sss = GetString(url,"
  • ");
    foreach(string str in sss)
    {
    Response.Write(str.ToString() +" ");
    }

    private string[] GetString(string str,string cutStr)
    {
    char[] cutChar = cutStr.ToCharArray();
    string[] sArray = str.Split(cutChar);
    return sArray;
    }

    2 字符串截取

    public static string GetFirstString(string stringToSub, int length)
    {
    Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
    char[] stringChar = stringToSub.ToCharArray();
    StringBuilder sb = new StringBuilder();
    int nLength = 0;
    bool isCut=false;
    for(int i = 0; i < stringChar.Length; i++)
    {
    if (regex.IsMatch((stringChar[i]).ToString()))
    {
    sb.Append(stringChar[i]);
    nLength += 2;
    }
    else
    {
    sb.Append(stringChar[i]);
    nLength = nLength + 1;
    }

    if (nLength > length)
    {
    isCut=true;
    break;
    }
    }
    if(isCut)
    return sb.ToString()+"...";
    else
    return sb.ToString();
    }

    3.取子串函数SubString
    string tmp2 = tmp1.SubString(0,3);
    相当于vb.net中的mid
    tring str="abcdefg";
    string str1=str.Substring(2,3);//str1="cde"

    4.C#中有什么函数可以判断某一字符串中是否存在着某一字符?如:"akkk*kkk"是否有“*”?

    string s = "akkk*kkk";
    int i = s.IndexOf("*");

    if( i != -1) 包含
    else 不包含

    5.右对齐此实例中的字符,在左边用指定的 Unicode 字符填充以达到指定的总长度。
    [C#] public string PadLeft(int, char);
    str = "256";
    str = str.PadLeft(5,"0"); //str = "00256"
  • 相关内容
    赞助商链接