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

asp.net 数组中字符串替换的几种方式

程序员文章站 2024-03-11 14:03:43
复制代码 代码如下://方法1 protected void page_load(object sender, eventargs e) { if (!page.ispos...
复制代码 代码如下:

//方法1
protected void page_load(object sender, eventargs e)
{
if (!page.ispostback)
{
replacestr();
}
}
public void replacestr()
{
arraylist myarray = new arraylist();
myarray.add("123");
myarray.add("aaa");
if (myarray.contains("aaa"))
{
myarray.remove("aaa");
myarray.add("bbb");
}
for (int i = 0; i <= myarray.count - 1; i++)
{
response.write(myarray[i].tostring());
}
}

//方法2
protected void page_load(object sender, eventargs e)
{
if (!page.ispostback)
{
replacestr();
}
}
public void replacestr()
{
string [] tm = new string[] { "123", "aaa" };
for (int i = 0; i < tm.length; i++)
{
if (tm[i].tostring() == "aaa")
{
tm[i]=tm[i].replace("aaa", "bbb");

}
}
for (int i = 0; i <= tm.length - 1; i++)
{
response.write(tm[i].tostring());
}
}
//方法3
protected void page_load(object sender, eventargs e)
{
if (!page.ispostback)
{
string[] tm = new string[] { "123", "aaa" };
string array=replacevalue(tm, "aaa", "bbb", ",");
response.write(array);
}
}
public static string replacevalue(string[] item, string oldsv, string newsv, string separator)
{
if (item == null) return string.empty;
stringbuilder sb = new stringbuilder();
foreach (string s in item)
{
if (s == oldsv)
{
sb.append(newsv);
sb.append(separator);
}
else
{
sb.append(s);
sb.append(separator);
}
}
string returnstr = sb.tostring();
returnstr = (returnstr.endswith(separator)) ? returnstr.substring(0, returnstr.length - 1) : returnstr;
return returnstr;
}