代码改变世界

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

  Virus-BeautyCode  阅读(574)  评论(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]”赋值 -- 它是只读的  
//.....................
我的思路是搞一个数组存放没有替换的和替换了的所有字符,不知各位有没有更好的呢,在这里先谢谢你的回复!!

编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示