首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在richtextbox中查找和替换文本

如何在richtextbox中查找和替换文本
EN

Stack Overflow用户
提问于 2018-09-05 02:37:07
回答 2查看 6.8K关注 0票数 1

我正在处理一个C# windows窗体,它执行以下操作:

我有一个显示文本文件内容的RichTextbox

我设法构建了一个带有搜索按钮的搜索框,供用户在此文件中搜索特定文本。但是,我还想创建一个查找文本框和按钮,以允许用户将找到的文本替换为他/她在文本框中输入的新文本,然后单击替换按钮。我该如何替换文本?...谢谢。

以下是搜索文本的代码:

代码语言:javascript
复制
 private void buttonSearch_Click(object sender, EventArgs e)
 {
     int index = 0;
     var temp = richTextArea.Text;
     richTextArea.Text = "";
     richTextArea.Text = temp;

     while (index < richTextArea.Text.LastIndexOf(textBoxSearch.Text))
     {
         richTextArea.Find(textBoxSearch.Text, index, richTextArea.TextLength, RichTextBoxFinds.None);
         richTextArea.SelectionBackColor = Color.Yellow;

         index = richTextArea.Text.IndexOf(textBoxSearch.Text, index) + 1;
     }
 }

wnform

EN

回答 2

Stack Overflow用户

发布于 2018-09-05 03:00:05

如果要替换文本中所有出现的搜索词:

代码语言:javascript
复制
richTextArea.Text = richTextArea.Text.Replace(textBoxSearch.Text, replaceTextBox.Text);
票数 0
EN

Stack Overflow用户

发布于 2018-09-05 03:26:20

我添加了两个按钮,一个用于将文件内容加载到富文本框中,另一个用于查找和替换文本,并将替换的内容再次写入文件。

代码语言:javascript
复制
private void Load_File_Contents_Click(object sender, EventArgs e)
    {
        try
        {
            //Below code will read the file and set the rich textbox with the contents of file
            string filePath = @"C:\New folder\file1.txt";
            richTextBox1.Text = File.ReadAllText(filePath);
        }
        catch (Exception ex)
        {
            lblError.Text = ex.Message;
        }
    }

    private void ReplaceAndWriteToFile_Click(object sender, EventArgs e)
    {
        try
        {
            string filePath = @"C:\New folder\file1.txt";

            //Find the "find" text from the richtextbox and replace it with the "replace" text
            string find = txtFind.Text.Trim(); //txtFind is textbox and will have the text that we want to find and replace
            string replace = txtReplace.Text.Trim(); //txtReplace is text and it will replace the find text with Replace text
            string newText = richTextBox1.Text.Replace(find, replace);
            richTextBox1.Text = newText;

            //Write the new contents of rich text box to file
            File.WriteAllText(filePath, richTextBox1.Text.Trim());
        }
        catch (Exception ex)
        {
            lblError.Text = ex.Message;
        }
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52172198

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档