maartenvdv
maartenvdv

Reputation: 177

How do I replace part of a string?

Supposed I have the following strings:

string str1 = "<tag tsdfg> some other random text";
string str2 = "<tag sdfgsdfgfsdg> some other random text";
string str3 = "<tag 1564> some other random text";

i would like to change those strings to

"<tag> some other random text"

Upvotes: 0

Views: 156

Answers (7)

James
James

Reputation: 82096

You could use a regular expression to replace all the arbitrary text inside the tag

Regex.Replace("<tag tsdfg> some random text", @"<(.*)?\s+(.*)?>", "<$1>");

This will effectively replace any text, after whitespace, at the end of any tag.

Try it out

Upvotes: 1

t3chb0t
t3chb0t

Reputation: 18655

Let's make it at least once unlike the other solutions not about removing or replacing but extracting ;-]

string str1 = "<tag tsdfg> some other random text";

Match match = Regex.Match(str1, @"\<(tag).+?\>(.+)");
string result = String.Format("<{0}>{1}", match.Groups[1].Value, match.Groups[2].Value);
Console.WriteLine(result );

Upvotes: 0

Masoud Mohammadi
Masoud Mohammadi

Reputation: 1739

you can do this:

str1="<tag>" + str1.Remove(0, str1.IndexOf(">") + 1);

it removes from index 0 to >+1 and then add it to "tag"

Upvotes: 0

w.b
w.b

Reputation: 11228

You can also do it this way:

string str = "<tag tsdfg> some other random text";

string newStr = new string(str.TakeWhile(c => !Char.IsWhiteSpace(c))
                              .Concat(str.SkipWhile(c => c != '>'))
                              .ToArray());

Console.WriteLine(newStr);  //  "<tag> some other random text" 

Upvotes: 0

Jcl
Jcl

Reputation: 28272

Use a regular expression:

str1 = Regex.Replace(str1, @"\<tag.*?\>", "<tag>");

Fiddle:

https://dotnetfiddle.net/LdokRn

Upvotes: 3

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

If after <tag there will always be a white-space ,then you can use Split() this way:

string str1 = "<tag tsdfg> some other random text";
string values = str1.Split(' ')[0]+">";

Upvotes: 1

Rohit
Rohit

Reputation: 1550

try

str1.Replace((str1.Substring(str1.IndexOf("<"), str1.IndexOf(">"))), "<tag>");

Upvotes: 1

Related Questions