无废话即兴编程一篇

实现“去掉字符串里的特定字符,并返回不包含该特定字符的一个新字符串”。Code is cheap,代码如下:

代码
 class Program
    {
        
static void Main(string[] args)
        {
            
string strTest = "-abc-d--AB-CD";
            
string result = GetFormatString(strTest, '-');//按照-分割
            Console.WriteLine(result);

            strTest 
= "yjeffywongy";
            result 
= GetFormatString(strTest, 'y');//按照y分割
            Console.WriteLine(result);

            strTest 
= null;//输入为空
            result = GetFormatString(strTest, '-');
            Console.WriteLine(result);

            Console.ReadKey();
        }

        
/// <summary>
        
/// 输入字符串,返回不包含特定分割字符的字符串
        
/// </summary>
        
/// <param name="strInput"></param>
        
/// <param name="splitChar"></param>
        
/// <returns></returns>
        public static string GetFormatString(string strInput, char splitChar)
        {
            
if (string.ReferenceEquals(strInput, null))
            {
                
//return null;
                throw new Exception("Input string is null.");
            }
            
if (strInput.IndexOf(splitChar) == -1)
            {
                
return strInput;
            }
            
char[] input = strInput.ToCharArray();
            
char[] result = new char[input.Length - 1];
            
int currentPos = 0;
            
bool isGetNext = false;
            
for (int i = 0; i < input.Length; i++)
            {
                
char c = input[i];
                
if (c == splitChar)
                {
                    isGetNext 
= true;
                }
                
else if (isGetNext)
                {
                    result[currentPos
++= c;
                    isGetNext 
= false;
                }
                
else
                {
                    result[currentPos
++= c;
                }
            }
            
return new String(result, 0, currentPos);
        }
    }

 最后还是要废话几句。本来这个功能就很简单,为什么还要记下来呢?因为第一次实现这个功能的时候,我是用string的split函数拆分成字符串数组然后再拼接完成的。您看到有什么不是很合理的地方了吗?没错,在函数里将string类型的变量加来加去的犯了string对象应用上的一个大忌(为什么string对象的变量加来加去就是大忌呢?不用我说了吧,因为这里是博客园)。你可能会说,stringbuilder对象已经有很不错的替代字符串拼接的方法,这个我当然知道(经常使用sb变量的人是不是也会和我一样会心一笑啊?)。不过上面的实现也是个人琢磨出来的,敝帚自珍,舍不得丢掉。不知道大家有没有更加快速和有技巧的实现方式?

原文地址:https://www.cnblogs.com/jeffwongishandsome/p/1678706.html