替换字符串中的char不起作用

时间:2015-04-17 21:30:09

标签: c#

我正在尝试替换字符串中的哈希字符,但以下内容不能正常工作

 string address = "Blk 344, Jurong West, Street 11, #02-111";
 address.Replace("#","%23");

任何想法都让我疯狂

查询字符串已满

http://localhost:54965/SKATEZ/thankyou.aspx?firstname=Fiora&lastname=Ray&address=Blk%20344,%20Jurong%20West,%20Street%2011,%20#02-111&total=22&nirc=S6799954H&country=Singapore&orderid=85&postalcode=746112

我按如下方式构建网址

string url = "thankyou.aspx?firstname=" + firstname + "&" + "lastname=" + lastname + "&" + "address=" + HttpUtility.EscapeDataString(address) + "&" + "total=" + total + "&" + "nirc=" + tbID.Text + "&" + "country=" + ddlCountry.SelectedValue + "&" + "orderid=" + orderid + "&" + "postalcode=" + tbPostalCode.Text;
Response.Redirect(url);

2 个答案:

答案 0 :(得分:8)

尝试

address = address.Replace("#","%23");

C#中的字符串是immutable

  

字符串不可变 - 创建对象后无法更改字符串对象的内容,尽管语法使其看起来好像可以执行此操作。例如,当您编写此代码时,编译器实际上会创建一个新的字符串对象来保存新的字符序列,并将该新对象分配给b。然后字符串“h”有资格进行垃圾回收。

答案 1 :(得分:0)

使用System.Uri.EscapeDataString(string)可以解决您的问题:

var urlbuilder = new StringBuilder();

urlbuilder.AppendFormat("thankyou.aspx?firstname={0}", firstname);
urlbuilder.AppendFormat("&lastname={0}", lastname);
urlbuilder.AppendFormat("&address={0}", System.Uri.EscapeDataString(address));
urlbuilder.AppendFormat("&total={0}", total);
urlbuilder.AppendFormat("&nirc={0}", tbID.Text);
urlbuilder.AppendFormat("&country={0}", ddlCountry.SelectedValue);
urlbuilder.AppendFormat("&orderid={0}", orderid);
urlbuilder.AppendFormat("&postalcode={0}", tbPostalCode.Text);

Response.Redirect(urlbuilder.ToString());

(使用System.Text.StringBuilder构建你的url使代码更具可读性)