代码改变世界

[原创]一个查找并且替换的算法

2007-09-06 10:10  Virus-BeautyCode  阅读(573)  评论(0编辑  收藏  举报
namespace ConsoleApp
{
 
    
class Program
    {

        
public static void Main()
        {
            
string input=Console.ReadLine();
            
string output = Program.Replace (input, "ab""00");
            System.Console.ReadLine();

        }

        
private static string Replace(string source, string a, string b)
        {
            
string result = source;
            
int position = 0;//发现的位置
            int len = 0;//
            int num = 0;//记录发现的要替换的个数

            
for (int i = 0; i < result.Length - 1; i++)
            {
                
if (result[i] == a[0])
                {
                    position 
= i;
                    len 
= 0;
                    
//int j = 0;

                    
while (len<=a.Length-1 && result[position + len] == a[len])
                    {
                        len
++;
                    }

                    
if (len == a.Length)
                    {
                        Console.WriteLine(
"find a positon");
                        num
++;
                        i 
= position+len;
                        Console.WriteLine(
"the posion is " + position + "\n the num is " + num);
                        
continue;
                    }

                    
if (a.Length == b.Length)
                    {

                        
for (int j = position; j < a.Length - 1; j++)
                        {
                            result[j] 
= a[j];
                        }
                    }
                    
else if (a.Length > b.Length)
                    {
 
                    }
                    
else
                    {

                    }
                }
            }
            
return "";
        }
    }
}

暂时实现了查找符合条件的个数和位置,替换的时候我想这样
if (a.Length == b.Length)
                    {

                        for (int j = position; j < a.Length - 1; j++)
                        {
                            result[j] = a[j];
                        }
                    }
                    else if (a.Length > b.Length)
                    {
 
                    }
                    else
                    {

                    }
要考虑三种情况,要查找的和要替换的字符串的长度相等,大于,小于。
相等就可以直接替换相应位置的字符就可以了,可是发现错误
////..............................
 无法对属性或索引器“string.this[int]”赋值 -- 它是只读的  
//.....................
我的思路是搞一个数组存放没有替换的和替换了的所有字符,不知各位有没有更好的呢,在这里先谢谢你的回复!!