Raised This Month: $ Target: $400
 0% 

Center Strings


Post New Thread Reply   
 
Thread Tools Display Modes
Author Message
Internet Bully
Member
Join Date: Apr 2014
Old 05-09-2014 , 00:07   Center Strings
Reply With Quote #1

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           " 

Last edited by Internet Bully; 05-09-2014 at 00:12.
Internet Bully is offline
KyleS
SourceMod Plugin Approver
Join Date: Jul 2009
Location: Segmentation Fault.
Old 05-09-2014 , 09:47   Re: Center Strings
Reply With Quote #2

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
KyleS is offline
Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -4. The time now is 03:02.


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