0

I want to find out how many spaces I need to use to create a string full of whitespaces that has the same width as another string. The font used is not monospaced, so different characters have different widths, is there any library that given a font and a string, returns the number of whitespaces to have the same width?

I can try character for character and find out how many whitespaces occupy the same or a similar width, but doing this for every character and for different fonts is very tedious.

  • 1
    Are you trying to align some text? – Fildor Nov 28 '22 at 15:38
  • [TextRenderer.MeasureText Method](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.textrenderer.measuretext?view=windowsdesktop-7.0) – 001 Nov 28 '22 at 15:40
  • Use the string constructor which takes a character and a count to makes a fixed size string with character repeated : string newString = new string(' ', count); – jdweng Nov 28 '22 at 15:41
  • What about using `\t` tab? – Tomas Paul Nov 28 '22 at 15:42

1 Answers1

0

is there any library that given a font and a string, returns the number of whitespaces to have the same width?

Maybe? but this is not the place to ask for libraries, and it should not be that hard to compute yourself.

Use Graphics.MeasureString or TextRenderer.MeasureText to measure your string, and the width of a single space. Divide the former with the later to get the number of spaces needed. Note that there is no guarantee that this will be an even number.

You might also want to read Why is Graphics.MeasureString() returning a higher than expected number?

JonasH
  • 28,608
  • 2
  • 10
  • 23