TheDizzle
TheDizzle

Reputation: 1574

Replacing values in a string using c#

I have a php example and am trying to replicate this in c#. What is the best way to do so? I can't seem to find what I'm looking for.

$string = 'The event will take place between :start and :end';

$replaced = preg_replace_array('/:[a-z_]+/', ['8:30', '9:00'], $string);

It fills in the :start and :end with the times in the array.

Upvotes: 0

Views: 61

Answers (2)

Krishna
Krishna

Reputation: 1985

No need of regex you can just you format

String.Format("The event will take place between {0} and {1}", "8:30", "9:00");

Upvotes: 2

AhmadReza Payan
AhmadReza Payan

Reputation: 2281

You could use either Composite formatting or String interpolation feature.

String.Format makes use of the composite formatting feature:

// Composite formatting:
var string = "The event will take place between {0} and {1}";
var replaced = String.Format(string, "8:30", "9:00");

Or use $ at the beginning of your string and pass the parameters into it very easily:

// String interpolation:
var replaced = $"The event will take place between {"8:30"} and {"9:00"}";

String interpolation provides a more readable and convenient syntax to create formatted strings than a string composite formatting feature.

Visit the following links for more information:

1. String.Format Method

2. $ - string interpolation

Upvotes: 2

Related Questions