按长度截取包含中文字符的字符串

 用于对客户端录入包含中文字符的校验很有用,防止保存到数据库中字段被截断。

//方法一:
public int Length(string strLen)
{
    
int l, t, c;
    
int i;
    l 
= strLen.Length;
    t 
= l;
    
for (i = 0; i < l; i++)
    
{
        c 
= (int) strLen[i];
        
if (c < 0)
        
{
            c 
= c + 65536;
        }

        
if (c > 255)
        
{
            t 
= t + 1;
        }

    }

    
return t;
}


//方法二:
public int Length(string strLen)
{
return Encoding.GetEncoding("GB18030").GetBytes(strSource).Length; 
   
}



public string Substring(string strValue, int startIndex, int length)
{
    
int iStartTemp = 0;
    
int iTemp = 0;
    
string returnString = "";
    
if (Length(strValue) > startIndex)
    
{
        
for (int i = 0; i < strValue.Length; i++)
        
{
            
int c = (int) strValue[i];
            
if (c < 0)
                c 
+= 65536;
            
if (c > 255)
                iTemp 
+= 2;
            
else
                iTemp 
+= 1;
            
if (iTemp > startIndex)
            
{
                iStartTemp 
= i;
                
break;
            }

        }

    }

    
else
        
return returnString;

    iTemp 
= 0;
    
if (Length(strValue) > (startIndex + length))
    
{
        
for (int i = iStartTemp; i < strValue.Length; i++)
        
{
            
int c = (int) strValue[i];
            
if (c < 0)
                c 
+= 65536;
            
if (c > 255)
                iTemp 
+= 2;
            
else
                iTemp 
+= 1;
            
if (iTemp > length)
                
break;
            
else
                returnString 
+= strValue[i].ToString();
        }

    }

    
else
    
{
        returnString 
= strValue.Substring(iStartTemp);
    }

    
return returnString;//注释文档
}

 

posted @ 2008-05-18 23:25  忠歌  阅读(269)  评论(0编辑  收藏  举报