Doubt with the language C#

Asked

Viewed 100 times

-1

I have a String any kind of "chair ".

Doubt

How do I give a space between all the letters in C#?

  • 3

    Welcome to Sopt Vinicius, you can edit your question instead of writing in the answer field ;) Already have some code written?

  • Possible duplicate of Doubt with string in c#

2 answers

2

You can do it this way, make sure that’s what you need.

string palavra = "palavra";
string nova_palavra = "";

foreach (var c in palavra)
{
    nova_palavra += c + " ";
}
nova_palavra = nova_palavra.Remove(nova_palavra.Length - 1);
Console.WriteLine(nova_palavra);

See the example running here: https://dotnetfiddle.net/YOkaVY

  • 1

    This solution leaves an additional space at the end of the word Thiago.

  • ready @Gustavosantos, I took the space there :) Thanks!

  • 1

    also meets, has several ways to do, including the one you posted, as it is a very simple problem the ways to solve are numerous..

2

There’s another way to do the same:

string palavra = "palavra";
string palavaComEspacos = string.Join(" ", palavra.ToCharArray());

Console.WriteLine(palavaComEspacos);

In this solution, the result is exactly what you search for, the Tochararray method returns an array of all the characters in the string, and the string. Join this array using a space (first parameter).

In addition, Join uses Stringbuilder, which avoids overloading of Garbage Colletor, you can find the implementation of the method in the official documentation: https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/string.cs

Dotnetfiddle: https://dotnetfiddle.net/bwUjWi

Browser other questions tagged

You are not signed in. Login or sign up in order to post.