Let's say you have a text field that supports 50 characters and your text is only 20 characters. You could get the text length, subtract that from the amount of characters the text field supports, and divide by two. Once you have that, then you can add that number of spaces at the beginnning.
Of course that solution doesn't work for everything, and if possible it's better to use some other idea.
There are various text justification algorithms, some better than others. For example, one simply asks, "How many words can I fit on the first line?" and then spreads those words evenly on the first line. Then it looks at the rest of the words.
A smart text justification algorithm does more to prevent abnormally poorly spaced lines, using a dynamic programming algorithm. I have never looked at the algorithm; I just know that's what it uses.