Suppose I have string s as given below , I want to have return substring with space like 123 456 7
string s = "123 456 789 012 7892";
string sa = Regex.Replace(s, @"\s", "").Substring(0, 7);
//string sa = "123456"; -- getting this after substring
// sa = "123 456 7" -- expected this after substring
CodePudding user response:
You can simply do it using Split
and Join
methods
string s = "123 456 789 012 7892";
var splitted = s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var joined = string.Join(' ', splitted);
var subString = joined.Substring(0, 9); // : 123 456 7
CodePudding user response:
you can use Regex.Replace(s, @"\s ", " ")
for replace multiple spaces in a string with one space
string s = "123 456 789 012 7892";
string newS = Regex.Replace(s, @"\s ", " ");
Console.WriteLine(newS.Substring(0, 7 2)); // 2 for spaces
result: "123 456 7"