Well, if you want a generic answer this is it:
Firt you must know the number of characters wide your display is. Then you must know the length of the string you wish to center on a line. From this, the basic algorithm is to emit the number of spaces which is HALF the difference between the line length and the string length. Example:
display is 80 chars wide
String is "This is a test" which is 14 characters.
Put out (80-14)/2 spaces, then the string, which is 33 spaces for this example line.
For an odd number, some wish to add an extra space and others wish to leave off the extra space. If you do integer arithmetic you will automatically drop the extra space for these cases. You can add extra code if you wish it to be the other way.
If your system supports it, you may issue a cursor positioning command instead of spaces, but the results are the same.
Also, if you are using a system that supports proportional fonts, then you must do the same thing except instead of counting characters you must measure the string width and know the screen width in pixels (or whatever unit your system uses). The same formula works but just use your unit of meaurement for screen width and string width instead. Then, instead of issuing spaces, you must use some sort of positioning that can get you positioned by pixel (or whatever unit of measurement you are using). This would be the case if you are coding, for example, in a window of a GUI instead of a text-mode terminal.
Unless you are really stuck, I will leave the coding up to you.
B-)
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.