How to put a char variable in a string through the keys { }?

Asked

Viewed 177 times

2

I’m doing an old-fashioned game, where there’s a function that prints it, and another that contains the 9 playable positions, I simplified the code so it doesn’t get too big and I just put a position.

There is a possibility of doing the same console.writeline, where we put the index and at the end of the string we put the variable?

private static char[] posJogaveis = { '_' };
public static string[] updateVelha()
{
string[] structVelha = { " _{0}_", posJogaveis[0].ToString() };
return structVelha;
}
private static string[] structVelha = updateVelha();

The idea was to change positions, but this method doesn’t exist or I’m doing it the wrong way:

inserir a descrição da imagem aqui

1 answer

4


You can do using String.Format thus:

String.Format("{0}", posJogaveis[0].ToString());

If you can use version C# 6.0 or higher, you have the option to use string interpolation. Using interpolation you just put one $ in front of the quotes, and when you need to show a variable, open Brackets and use the variable closing immediately afterwards. Example:

$"_{ posJogaveis[0] }_";

In the case of more than one position:

$"_{ posJogaveis[0] }_|_{ posJogaveis[1] }_|_{ posJogaveis[2] }_";

More information on string interpolation

  • 1

    So in the end I don’t need to say which variable it is, just put it in the string exactly as you did?

  • Yes, by interpolation you do nothing at the end, you really put the variables where they should be as I put example. And you don’t need Tostring, it’s redundant.

  • Just a reminder that string interpolation is only available from C#6 onwards.

  • Really, I forgot the detail of the version and also was not specified by the author, but I will add anyway.

Browser other questions tagged

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