Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a character only in the start of a string

I want to replace a character ":" with a space " " character only in the beginning of a string, if the ":" character is present in the beginning. The TrimStart(":".ToCharArray()) removes the character not replaces it. And Replace(":", " ") replaces all the occurrences of the character even if they are not in start. What is the solution? Can Regex be used for it? Or any other way? The desired result is:

:abc -> abc
abc  -> abc
a:bc -> a:bc
abc: -> abc:
like image 753
Sourabh Avatar asked Jun 25 '13 19:06

Sourabh


People also ask

How do you replace only one character in a string?

Answer: Use the JavaScript replace() method You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global ( g ) modifier.

How do you change the start of a string in Java?

You should use string. replaceFirst("^demo", "xyz"). ^ matched the beginning of the string.

How do you replace only one occurrence of a string in Python?

>>> help(str. replace) Help on method_descriptor: replace(...) S. replace (old, new[, count]) -> string Return a copy of string S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.


1 Answers

You can use this regular expression:

var output = Regex.Replace(input, "^:", " ");

But for something this simple, I'd recommend using conventional string methods:

var output = 
    (!string.IsNullOrEmpty(input) && input[0] == ':') 
    ? " " + input.Substring(1) : input;

Note: the check for null or empty strings may not be necessary in your case.

like image 163
p.s.w.g Avatar answered Sep 30 '22 06:09

p.s.w.g