AlliedModders

AlliedModders (https://forums.alliedmods.net/index.php)
-   Snippets and Tutorials (https://forums.alliedmods.net/forumdisplay.php?f=112)
-   -   Center Strings (https://forums.alliedmods.net/showthread.php?t=240098)

Internet Bully 05-09-2014 00:07

Center Strings
 
PHP Code:

public CenterString(const String:str[], String:output[], maxlength)
{
    new 
length strlen(str);
    new 
size     maxlength;
    new 
String:newstr[size];
    new 
firstspace RoundToCeil((size-length)/2.0);
    new 
secondspace RoundToFloor((size-length)/2.0);
    
    for(new 
i=0firstspacei++)
    {    
        
newstr[i] = ' '// change this if you want to center with non-whitespace
    
}
    
    
StrCat(newstrsizestr);
    
    for(new 
j=length+firstspacelength+firstspace+secondspacej++)
    {    
        
newstr[j] = ' '// change this if you want to center with non-whitespace
    
}
    
    
strcopy(outputmaxlengthnewstr);


Useful if you're printing text and want it centered, also not a bad example of how to use a buffer to return strings.

Example:
PHP Code:

new String:test[32]; 
strcopy(testsizeof(test), "Centering");
CenterString(testtestsizeof(test)); 

returns:
PHP Code:

 "            Centering           " 


KyleS 05-09-2014 09:47

Re: Center Strings
 
PHP Code:

stock CenterString(String:sBuffer[], outlen, const String:sInput[], inlen = -1)
{
    static const 
String:sTokenHack[] = "%%%us%%s%%%us";
    
decl String:sTempBuff[24];

    if (
inlen == -1)
    {
        
inlen strlen(sInput);
    }

    
inlen = (outlen >> 1) - (inlen >> 1);

    
FormatEx(sTempBuffsizeof(sTempBuff), sTokenHackinleninlen);
    return 
Format(sBufferoutlensTempBuff""sInput"");


atcprintf doesn't appear to support %*s, so we have that horrible static const at the top (and double format). Anyways, hopefully this helps someone :bee:


All times are GMT -4. The time now is 10:09.

Powered by vBulletin®
Copyright ©2000 - 2024, vBulletin Solutions, Inc.