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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

  2021-03-18 我要评论
想了解C#中怎样从指定字符串中查找并替换字符串?的相关内容吗,在本文为您仔细讲解从指定字符串中查找并替换字符串的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:查找,替换,字符串,下面大家一起来学习吧。

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;
        }

    }
}

实验结果:

 

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们