程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#基礎知識 >> C#中怎樣從指定字符串中查找並替換字符串?

C#中怎樣從指定字符串中查找並替換字符串?

編輯:C#基礎知識

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

    }
}

實驗結果:

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved