VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > C#教程 >
  • c#的字符串基础学习

制作者:剑锋冷月 单位:无忧统计网,www.51stat.net
 

  在C#中字符串是System.String类的一个引用类型,但与其他引用类型不同的是,C#将字符串视为一个基本类型:可以声明为一个常量,并可以直接赋值。

  字符串的操作

  (1)索引

  使用foreach或while对string来提取字符串中的字符,在这些情况下,操作都是只读的。

   strngmyString="Helloworld";
   foreach(charcinmyString)
   {
       Console.Write(c.ToString());
   }

 

  (2)连接

  用+号连接字符串,但这种方法,在连接过程会将新的组合字符串分配新的空间,在一个较大的循环中会占用过多的资源,因此这种情况下会使用StringBuild类来代替连接操作符。

  (3)抽取和定位

  SubString方法在字符串中抽取所选的部分。这里给处此方法的两个重载形式:

    stringpoem="InXanadudidKublaKhan";
    stringreslut;
    reslut=poem.Substring(10);    //didKublaKhan
    reslut=poem.Substring(0,9);   //InXanadu
   
    IndexOf()

 

  该方法用于定位字符模式在字符串中出现的位置,有三种重载形势,Index(str,m,n)表示str在字符串中从m到n之间第一次出现的位置。字符串的第一个位置为0,搜索结果为空时方法返回-1。

  下面是一个确定字符串出现的方法:

     //Methodtocounttheoccurrencesoftextinagivenstring
    publicstaticintCharCount(StringstrSource,StringstrToFind)
    {
      intiCount=0;//stringtypehsindexof0
  intiPos=strSource.IndexOf(strToFind);
      while(iPos!=-1)
      {
        iCount++;
        iPos=strSource.IndexOf(strToFind,iPos+1);
      }
      returniCount;
    }
    staticvoidMain(string[]args)
    {
      strings="abcdead";
      inta=s.IndexOf("a",1);
      Console.Write(a);
    } 

 

  (3)比较

  System.String中有四个比较方法:Compare、CompareOrdinal、CompareTo和Equals,比较字符串的复杂性在区分大小写、语言、字符集及文化因素。

  Compare()方法是CompareTo()方法的静态版本。只要使用“=”运算符,就会调用Equals()方法,的以Equals()方法与“=”是等价的。CompareOrdinal()方法对两个字符串比较不考本地语言与文件。

  (4)复制

  Copy()静态方法。

  CopyTo()方法。

  (5)分割

  split()此方法返回一个字符串数组,其中每个元素是一个单词。作为输入,split采用一个字符数组指示哪些字符被用作分隔符。本示例中使用了空格、逗号、句点、冒号和制表符。

    char[]delimiterChars={’’,’,’,’.’,’:’,’  ’};
    stringtext="one  twothree:four,fivesixseven";
    System.Console.WriteLine("Originaltext:’{0}’",text);
  string[]words=text.Split(delimiterChars);
    System.Console.WriteLine("{0}wordsintext:",words.Length);
    foreach(stringsinwords)
    {
      System.Console.WriteLine(s);
    }

 



相关教程