String.Substring 方法
名称 说明
String.Substring (Int32) 从此实例检索子字符串。子字符串从指定的字符位置开始。
String.Substring (Int32, Int32) 从此实例检索子字符串。子字符串从指定的字符位置开始且具有指定的长度。
举例如下:

using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
     class Program
     {
         static void Main(string[] args)
         {
             string s = "Hello C# World!";
             //s1为从s中截取的位置为3的字符以后的字符子串,3表示子字符串的起始字符位置
            string s1=s.Substring(3);
             Console.WriteLine(s1);
             //s2为从s中截取的位置为6的字符开始长度为2的字符串,6表示子字符的起始字符位置,2表示子字符长度
            string s2 = s.Substring(6, 2);
             Console.WriteLine(s2);
        }
     }
}

 

结果如下:
lo C# World!
C#
随即在附上一个C#截取字符串函数

public string getString(string RawString, Int32 Length)
     {
         if (RawString.Length <= Length)
         {
             return RawString;
         }
         else
         {
             for (Int32 i = RawString.Length - 1; i >= 0; i--)
             {
                 if (System.Text.Encoding.GetEncoding("GB2312").GetByteCount(RawString.Substring(0, i)) < Length)
                 {
                     return RawString.Substring(0, i) + "...";
                 }
             }
             return "...";
         }
     }

		///  
		/// 截取字符串,不限制字符串长度 
		///  
		/// 待截取的字符串 
		/// 每行的长度,多于这个长度自动换行 
		///  
         public string CutStr(string str,int len) 
         {     string s=""; 
            
             for(int i=0;i"; 
                     } 
                         
                 } 
                 else if (i>last) 
                 { 
                     s+=str.Substring(i-1) ; 
                     break; 
                 } 
                 
             } 
             
             return s; 
             
         } 
 

         ////  
         /// 截取字符串并限制字符串长度,多于给定的长度+。。。 
         ///  
         /// 待截取的字符串 
         /// 每行的长度,多于这个长度自动换行 
         /// 输出字符串最大的长度 
         ///  
         public string CutStr(string str,int len,int max) 
         { 
             string s=""; 
             string sheng=""; 
            if (str.Length >max) 
            { 
                 str=str.Substring(0,max) ; 
                 sheng=""; 
             } 
             for(int i=0;i"; 
                     } 
                        
                 } 
                 else if (i>last) 
                 { 
                     s+=str.Substring(i-1) ; 
                     break; 
                 } 
                
             } 
             
             return s+sheng; 
             
} 

标签: none

添加新评论