欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#中怎样从指定字符串中查找并替换字符串?

程序员文章站 2024-02-10 18:34:22
using system;using system.collections.generic;using system.componentmodel;using system...

using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.windows.forms;
#region             
#endregion
namespace find
{
    public partial class form1 : form
    {
        public form1()
        {
            initializecomponent();
            string str = "";
            richtextbox1.text = str;
        }
        int start = 0;
        int count = 0;
        /// <summary>
        /// 查找字符串
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void find_click(object sender, eventargs e)
        {
            string str1;
            str1 = txt_find.text;
            if (start >= richtextbox1.text.length)
            {
                messagebox.show("以查找到尾部");
                start = 0;
            }
            else
            {
                start = richtextbox1.find(str1, start, richtextboxfinds.matchcase);
                if (start == -1)
                {
                    if (count == 0)
                    {
                        messagebox.show("没有该字符!");
                    }
                    else
                    {
                        messagebox.show("以查找到尾部!");
                        start = 0;
                    }
                }
                else
                {
                    start = start + str1.length;
                    richtextbox1.focus();
                }
            }
        }
        /// <summary>
        /// 替换字符串
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void replace_click(object sender, eventargs e)
        {
            richtextbox1.text = richtextbox1.text.replace(txt_find.text, txt_replace.text);
        }
        /// <summary>
        /// 输入查找的字符串
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txt_find_textchanged(object sender, eventargs e)
        {
            string str1;
            str1 = txt_find.text;
            start = 0;
            count = 0;
        }

    }
}

实验结果:

 

C#中怎样从指定字符串中查找并替换字符串?C#中怎样从指定字符串中查找并替换字符串?

C#中怎样从指定字符串中查找并替换字符串?