我有一个像
这样的字符串<link rel='stylesheet' href='/abc/def/ghi/default.css' type='text/css' media='screen' />
现在,我想提取“/abc/def/ghi/default.css”并将其传递给函数foo
void foo(string str)
{
//some logic
return str; //suppose it returns /abc/def/ghi/default.css/v=123
}
我想将它追溯到我原来的字符串,如
<link rel='stylesheet' href='/abc/def/ghi/default.css/v=123' type='text/css' media='screen' />
我尝试使用substring,但是alwals内容更改,我可以从“href”开始查找字符串,但我不知道href会有多长。
答案 0 :(得分:0)
如果您在&#39; href&#39;之后识别开始和结束单引号,您仍然可以使用子字符串。字符串中的标识符。
public string foo(string inputString)
{
string result = "";
int hrefIndex = inputString.IndexOf("href=");
int firstQuoteIndexAfterHref = -1;
int secondQuoteIndexAfterHref = -1;
if (hrefIndex != -1)
{
firstQuoteIndexAfterHref = inputString.IndexOf("'", hrefIndex + 1);
Console.Out.WriteLine("hrefIndex={0}, firstQuoteIndex={1}", hrefIndex, firstQuoteIndexAfterHref);
if (firstQuoteIndexAfterHref != -1)
{
secondQuoteIndexAfterHref = inputString.IndexOf("'", firstQuoteIndexAfterHref + 1);
result = string.Format("{0}/v=123",inputString.Substring(firstQuoteIndexAfterHref, secondQuoteIndexAfterHref - firstQuoteIndexAfterHref + 1));
}
}
return result;
}
答案 1 :(得分:0)
你可以这样做:
public string foo(string str)
{
var StartIndex = str.IndexOf("href");
var firstapostrophe = str.IndexOf("'",StartIndex);
var secondapostrophe = str.IndexOf("'", firstapostrophe);
var result = str.Replace(str.Substring(firstapostrophe, secondapostrophe - 2),
str.Substring(firstapostrophe, secondapostrophe - 2) + "/v=123");
return result;
}
答案 2 :(得分:0)
简单地将其视为xml,请看一下:
using System;
using System.Xml;
using System.Xml.Linq;
public class Program
{
public static void Main()
{
var s = "<link href='aaa' />";
var doc = XDocument.Parse(s);
var link = doc.Element("link");
var href = link.Attribute("href");
href.Value = "bbb";
s = doc.ToString();
Console.WriteLine(s);
}
}