asp.net 数组中字符串替换的几种方式
程序员文章站
2024-03-09 10:48:23
复制代码 代码如下://方法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;
}
上一篇: 复制文件夹