小虫快跑

.net爱好者

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

以指定字符串分割,去除某段字符的函数。

哈哈,不知道哪里还存在错误。。
反正测试了下,比用String.Split()要快一半吧,当字符串很长的时候。。。
Hoho大家给看看哪里会有异常~!~

第一次发东西,大家不要扔鸡蛋啊,好像没说太清楚哈哈

        /// <summary>
        
/// 将以指定字符分割的字符串,从指定位置去除
        
/// </summary>
        
/// <param name="str">要操作的字符串</param>
        
/// <param name="keyId">分割位置,从0起</param>
        
/// <param name="indexStr">分割用的字符串</param>
        
/// <returns>去除后的字符串,失败返回其本身</returns>
        public static string RemoveStrIndexStr(string str, int keyId, string indexStr)
        {
            
//如果测试不通过,返回其本身
            if (str == null || indexStr == null || str == string.Empty || indexStr == string.Empty || keyId >= str.Length)
                
return str;
            
int beginIndex = 0;
            
int endIndex = 0;
            
//循环找出字符串的开始位置
            for (int i = 0; i < keyId; i++)
            {
                {
                    beginIndex 
= str.IndexOf(indexStr, beginIndex);
                    
if (beginIndex == -1)
                        
break;
                    beginIndex
++;
                }
            }
            
//如果开始位置获取错误,说明指定数字超过所索引数,返回本身
            if (beginIndex < 0)
                
return str;
            
//字符串的结束位置
            endIndex = str.IndexOf(indexStr, beginIndex);
            
//如果没有检索到分割字符,则将结束位置定为字符长度
            if (endIndex == -1)
            {
                endIndex 
= str.Length;
                
if (beginIndex > 0)
                    beginIndex
--;
            }
            
else
                endIndex
++;
            
//当开始位置和结束位置都存在,切开是结束位不相等的情况下进行字符串替换
            if (beginIndex < endIndex)
            {
                
//得到要去除的字符串长度
                str = str.Remove(beginIndex, endIndex - beginIndex);
            }
            
return str;
        }

posted on 2007-11-16 08:45  最坏是单飞  阅读(536)  评论(0)    收藏  举报