我有一个字符串,
string ij = "/alwaysSame09102012/myThing.aspx?asdasd=99&Urasdl=scashdasdeasdmeasds/tasdigaesdr1/gasdoasdveasdasdrnaasdancasde/eamsdeasdetiasdasdnagsds/tasidgeasdr1masdeetasdasd11180,/reasdMeasdetMe2as0d1asd0/asrdganasdiseasdasdgeasdetasdiasdngaasdsd.aasdspafsxasdffas?asdsdlaieasdnedtfe=asdsafaser1meafswedfhfdget111ertert80"
现在我只需要用“always2013forever”更改第一个“alwaysSame09102012”。
我知道我可以做这样的事情,
string ij = "/alwaysSame09102012/myThing.aspx?asdasd=99&Urasdl=scashdasdeasdmeasds/tasdigaesdr1/gasdoasdveasdasdrnaasdancasde/eamsdeasdetiasdasdnagsds/tasidgeasdr1masdeetasdasd11180,/reasdMeasdetMe2as0d1asd0/asrdganasdiseasdasdgeasdetasdiasdngaasdsd.aasdspafsxasdffas?asdsdlaieasdnedtfe=asdsafaser1meafswedfhfdget111ertert80"
string[] c = ij.split['/'];
string finalString = ij.replace( "/" + c[0] + "/", "/" + "always2013forever" + "/");
这是我的逻辑,但没有工作,请帮忙,
我的字符串中只有常量"/alwaysSame09102012/"
,我需要替换
更新
**
**
答案 0 :(得分:5)
例如:
var goodStr = ij.Replace("alwaysSame09102012", "always2013forever");
您的答案不起作用的原因是因为c[0]
将是""
。您要查找的值(例如“alwaysSame09102012”)将位于c[1]
。
答案 1 :(得分:1)
string ij = "/alwaysSame09102012/myThing.aspx?asdasd=99&Urasdl=scashdasdeasdmeasds/tasdigaesdr1/gasdoasdveasdasdrnaasdancasde/eamsdeasdetiasdasdnagsds/tasidgeasdr1masdeetasdasd11180,/reasdMeasdetMe2as0d1asd0/asrdganasdiseasdasdgeasdetasdiasdngaasdsd.aasdspafsxasdffas?asdsdlaieasdnedtfe=asdsafaser1meafswedfhfdget111ertert80"
string newString = ij.Replace("alwaysSame09102012","always2013forever");
答案 2 :(得分:1)
string ReplaceFirst (string source, string old_substring, string new_substring)
{
var position = source.IndexOf(old_substring);
return (position < 0)
? source
: source.Substring(0, position) + new_substring + source.Substring(position + old_substring.Length);
}
用法:
var new_string = ReplaceFirst("/alwaysSame09102012/myThing...", "alwaysSame09102012","always2013forever");
答案 3 :(得分:0)
您应该使用URI类。
http://msdn.microsoft.com/en-us/library/system.uri.aspx http://msdn.microsoft.com/en-us/library/system.uribuilder.aspx
这将为您提供更大的灵活性,并防止您逃避问题等。