如何从字符串中分割数据?

时间:2011-11-14 10:20:44

标签: c# string split

如何从字符串中分割数据?

我有这样的字符串,

Url=http://www.yahoo.com UrlImage=http://l.yimg.com/a/i/ww/met/yahoo_logo_in_061509.png UrlTitle=Yahoo! India UrlDescription=Welcome to Yahoo!, the world's most visited home page. Quickly find what you're searching for, get in touch with friends and stay in-the-know with the latest news and information.

我希望将此信息拆分为

http://www.yahoo.com

http://l.yimg.com/a/i/ww/met/yahoo_logo_in_061509.png

Yahoo! India

Welcome to Yahoo!, the world's most visited home page. Quickly find what you're searching for, get in touch with friends and stay in-the-know with the latest news and information.

如何将上面的字符串分成这四个部分并保存到每个部分的临时变量中?

string url = http://www.yahoo.com

string urlImage = http://l.yimg.com/a/i/ww/met/yahoo_logo_in_061509.png

string urlTitle = Yahoo!印度

string urlDescription =欢迎来到雅虎!这是全球访问量最大的主页。快速找到您要搜索的内容,与朋友取得联系并随时了解最新消息和信息。

我该怎么做?

2 个答案:

答案 0 :(得分:6)

假设输入字符串的格式不会改变(即键的顺序),你可以尝试这样的事情:

var input = "Url:http://www.yahoo.com UrlImage:http://l.yimg.com/a/i/ww/met/yahoo_logo_in_061509.png UrlTitle:Yahoo! India UrlDescription:Welcome to Yahoo!, the world's most visited home page. Quickly find what you're searching for, get in touch with friends and stay in-the-know with the latest news and information."

// Convert the input string into a format which is easier to split...
input = input.Replace("Url=", "")
             .Replace("UrlImage=", "|")
             .Replace("UrlTitle=", "|")
             .Replace("UrlDescription=", "|");

var splits = input.Split("|");

string url         = splits[0]; // = http://www.yahoo.com
string image       = splits[1]; // = http://l.yimg.com/a/i/ww/met/yahoo_logo_in_061509.png
string title       = splits[2]; // = Yahoo! India
string description = splits[3]; // = Welcome to Yahoo!, the world's...

答案 1 :(得分:0)

你可以试试这个:

var input = "Url:http://www.yahoo.com UrlImage:http://l.yimg.com/a/i/ww/met/yahoo_logo_in_061509.png UrlTitle:Yahoo! India UrlDescription:Welcome to Yahoo!, the world's most visited home page. Quickly find what you're searching for, get in touch with friends and stay in-the-know with the latest news and information.";

var result = input.Split(new []{"Url:","UrlImage:","UrlTitle:","UrlDescription:"}, StringSplitOptions.RemoveEmptyEntries);