Nave Tseva
Nave Tseva

Reputation: 878

How to separate string to more than one part C#

I have a string, that contains links. Example:

www.google.com;www.yahoo.com;www.gmail.com

My question is how can I separate those links so I can add to all the links the tag <a> and in the end of the link the tag </a>?

I should get this:

<a>www.google.com</a>;<a>www.yahoo.com</a>;<a>www.gmail.com</a>

I will be thankful if the solution will be simple as possible and use the IndexOf method.

Upvotes: 1

Views: 121

Answers (5)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

The easiest way:

var result = "<a>" + String.Join("</a>;<a>", input.Split(new char[] { ';' })) + "</a>";

However, it will return <a></a> for empty input.

Explanation:

input.Split(new char[] { ';' }) splits input string by : character.

String.Join("</a>;<a>", input.Split(new char[] { ';' })) joins elements from the split using </a>;<a> string.

"<a>" + String.Join("</a>;<a>", input.Split(new char[] { ';' })) + "</a>"; adds additional <a> in front and </a> at the end of results.

Upvotes: 2

Mudassir Hasan
Mudassir Hasan

Reputation: 28741

Use split() function . Split string by character ; and store in an array.

string[] arr = inputstring.Split(';'); 
string outputstring=string.Empty;
for(int i=0;i<arr.Length;i++)
  outputstring += "<a>"+arr[i]+"</a>;";

Since you don't want semicolon at end

outputstring = outputstring .TrimEnd(';');

Upvotes: -1

ilyabreev
ilyabreev

Reputation: 634

Try something like this:

var result = String.Join(";", 
"www.google.com;www.yahoo.com;www.gmail.com"
.Split(';')
.Select(str => String.Format("<a>{0}</a>", str)));

Upvotes: 2

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

var links = "www.google.com;www.yahoo.com;www.gmail.com";
var result = String.Join(";", links.Split(';').Select(s => String.Format("<a>{0}</a>", s)));

Upvotes: 3

Dima
Dima

Reputation: 6741

That code should do the job:

var input = "www.google.com;www.yahoo.com;www.gmail.com";
var result = string.Join(";", input.Split(';').Select(x => string.Format("<a>{0}</a>",x)));

Upvotes: 5

Related Questions