Suppose the string "Hello World" is given, I need to get the string "H ello W orld" How can I do this in C #?
- And instead of a space between words should be two spaces or one? - Alexey Shimansky
|
2 answers
If instead of a space between words there should be only one space, and not two, then so:
string test = "Hello world"; test = test.Replace(" ", string.Empty); var result = String.Join(" ", test.ToCharArray()); Console.WriteLine(result); If instead of a space, you make two spaces (that is, consider it to be the same equal character as the letters in the string), then you just need to comment out the line
test = test.Replace(" ", string.Empty); Replace - Returns a new line in which all occurrences of the specified line in the current instance are replaced by another specified line.
ToCharArray - splits a string into a char array
Join - Interconnects the specified elements of the array of strings, placing between them the specified separator.
- You can just say: ideone.com/xScYru - VladD
- @VladD did not know, until today) - Alexey Shimansky
|
You can regular:
string input = "Hello World"; var result = Regex.Replace(input, "(.)", "$1 "); You can brute force:
string input = "Hello World"; StringBuilder result = new StringBuilder(); foreach (var chr in input) { result.Append(chr+ " "); } result = result.ToString().TrimEnd(); You can also use LINQ:
string input = "Hello World"; string result = string.Join("", input.Select(x => x + " ")); - in a loop, the result type is best changed to StringBuilder and use the Append () method. In the current view, the cycle will generate tons of garbage lines. - rdorn
- @rdorn, yes indeed. Corrected. - iluxa1810 9:09
|