运行以下代码时,我得到运行时异常fix:Index
超出了数组的范围:
char[] delim = { ' ' };
string sContent = txtcontent.Text;
string sFind = txtfind.Text;
string sReplace = txtreplace.Text;
string sRecontent = txtrepalcecontent.Text;
//Session["find"] = sFind;
string[] fileLineString = new string[sContent.Length];
for (int i =0 ; i < sContent.Length; i++)
{
//fileLineString[0] = sContent[0].ToString();
string[] content = sContent.Split(delim);
if (sFind == content[i]) ////**error**
//if (Session["find"].ToString() == content[i])
{
string A = sContent.Remove(i, txtfind.Text.Length);
string S = A.Insert(i, sReplace);
txtrepalcecontent.Text = S;
}
答案 0 :(得分:0)
问题在于:
string[] content = sContent.Split(delim);
if (sFind == content[i]) ////**error**
你正在迭代一个长度为nm的数组,m是另一个数组的长度(更短,因为数组是拆分的结果,所以你要删除字符并减少长度),但仍然期待数组长度为n。这是你让索引超出界限的方式。 要修复它,只需在for-cycle之前移动拆分并使用相同的索引进行迭代:
char[] delim = { ' ' };
string sContent = txtcontent.Text;
string sFind = txtfind.Text;
string sReplace = txtreplace.Text;
string sRecontent = txtrepalcecontent.Text;
//Session["find"] = sFind;
string[] content = sContent.Split(delim);
string[] fileLineString = new string[content.Length];
for (int i =0 ; i < content.Length; i++)
{
//fileLineString[0] = sContent[0].ToString();
if (sFind == content[i]) ////**error**
//if (Session["find"].ToString() == content[i])
{
string A = sContent.Remove(i, txtfind.Text.Length);
string S = A.Insert(i, sReplace);
txtrepalcecontent.Text = S;
}
答案 1 :(得分:0)
string A = sContent.Remove(i, txtfind.Text.Length);
string S = A.Insert(i, sReplace);
txtrepalcecontent.Text = S;
如何在没有替换功能的情况下进行替换