积极答复者
关于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;
namespace 文件操作
{
public partial class FindAndReplace : Form
{
MainForm frmMain;
public FindAndReplace(MainForm mainform)
{
InitializeComponent();
frmMain = mainform;
}
int intStart;// 开始位置
int intEnd;
private void btnFindNext_Click(object sender, EventArgs e)
{
string strText = frmMain.textBox1.Text;//原始文本
string strFind = txtFind.Text;//带查找的文本
int intLength = strFind.Length; // 带查找文本的长度
string strT;//临时变量
if (radioDown.Checked == true) //向下
{
for (; intStart <= strText.Length - intLength; intStart++)
{
strT = strText.Substring(intStart, intLength);
if (chkCapital.Checked == false)//不区分大小写
{
if (strT == strFind) break;
}
else//区分大小写
{//ToUpper函数作用将字符转成大写
if (strT.ToUpper() == strFind.ToUpper()) break;
}
}
if (intStart < strText.Length - 1)
{
frmMain.textBox1.Select(intStart, intLength);//让textBox1获取焦点;(找到后标记出来)
frmMain.textBox1.Focus();
intStart++;//查找完后继续
}
else//查找不到则重新开始
intStart = 0;
}
else if (radioUp.Checked == true)//向上
{
int intEnd = strText.Length;
for (; intEnd - intLength >= 0; intEnd--)
{
strT = strText.Substring(intEnd - intLength, intLength);
if (chkCapital.Checked == false)//不区分大小写
{
if (strT == strFind) break;
}
else//区分大小写
{//ToUpper函数作用将字符转成大写
if (strT.ToUpper() == strFind.ToUpper()) break;
}
if (intEnd >=intLength )
{
frmMain.textBox1.Select(intEnd - intLength, intLength);//让textBox1获取焦点;(找到后标记出来)
frmMain.textBox1.Focus();
intEnd--;//查找完后继续
}
else//查找不到则重新开始
intEnd = strText.Length;
}
}
}
private void findAndReplace_Load(object sender, EventArgs e)
{
intStart = 0;
intEnd = frmMain.textBox1.Text.Length ;
}
private void txtFind_TextChanged(object sender, EventArgs e)
{
if (radioDown.Checked == true)
{
intStart = 0;
}
else if (radioUp.Checked == true)
{
intEnd = frmMain.textBox1.Text.Length;
}
}
}
}
答案
-
向上查找,你的循环没有结束就进行字符选择和高亮,所以你的代码应该要结束循环
还有,每次向上,你都初始化了intEnd ,导致每次都是从尾部开始查找,所以代码应改为:
else if (radioUp.Checked == true)//向上 { // int intEnd = strText.Length; for (; intEnd - intLength >= 0; intEnd--) { strT = strText.Substring(intEnd - intLength, intLength); if (chkCapital.Checked == false)//不区分大小写 { if (strT == strFind) break; } else//区分大小写 {//ToUpper函数作用将字符转成大写 if (strT.ToUpper() == strFind.ToUpper()) break; } } if (intEnd >= intLength) { frmMain.textBox1.Select(intEnd - intLength, intLength);//让textBox1获取焦点;(找到后标记出来) frmMain.textBox1.Focus(); intEnd--;//查找完后继续 } else//查找不到则重新开始 intEnd = strText.Length; }
Bob Bao
- 已标记为答案 金k 2016年11月21日 13:21