简体   繁体   中英

How to pad char array with empty spaces on left and right hand side of the text

I am fairly new with C++ so for some people the answer to the quesiton I have might seem quite obvious. What I want to achieve is to create a method which would return the given char array fill with empty spaces before and after it in order to meet certain length. So the effect at the end would be as if the given char array would be in the middle of the other, bigger char array.

Lets say we have a char array with HelloWorld. I want the method to return me a new char array with the length specified beforehand and the given char array "positioned" in the middle of returning char array.

char ch[] = "HelloWorld";
char ret[20];                           // lets say we want to have the resulting char array the length of 20 chars
char ret[20] = "     HelloWorld     ";  // this is the result to be expected as return of the method

In case of odd number of given char array would like for it to be in offset of one space on the left of the middle. I would also like to avoid any memory consuming strings or any other methods that are not in standard library - keep it as plain as possible. What would be the best way to tackle this issue? Thanks!

There are mainly two ways of doing this: either using char literals (aka char arrays), like you would do in C language or using built-in std::string type (or similar types), which is the usual choice if you're programming in C++, despite there are exceptions. I'm providing you one example for each.

First, using arrays, you will need to include cstring header to use built-in string literals manipulation functions. Keep in mind that, as part of the length of it, a char array always terminates with the null terminator character '\0' (ASCII code is 0), therefore for a DIM -dimensioned string you will be able to store your characters in DIM - 1 positions. Here is the code with comments.

constexpr int DIM = 20;

char ch[] = "HelloWorld";
char ret[DIM] = "";

auto len_ch = std::strlen(ch);      // length of ch without '\0' char
auto n_blanks = DIM - len_ch - 1;   // number of blank chars needed
auto half_n_blanks = n_blanks / 2;  // half of that

// fill in from begin and end of ret with blanks
for (auto i = 0u; i < half_n_blanks; i++)
    ret[i] = ret[DIM - i - 2] = ' ';

// copy ch content into ret starting from half_n_blanks position
memcpy_s(
    ret + half_n_blanks,    // start inserting from here
    DIM - half_n_blanks,    // length from our position to the end of ret
    ch,                     // string we need to copy
    len_ch);                // length of ch

// if odd, after ch copied chars
// there will be a space left to insert a blank in
if (n_blanks % 2 == 1)
    *(ret + half_n_blanks + len_ch) = ' ';

I chose first to insert blank spaces both to the begin and to the end of the string and then to copy the content of ch .

The second approach is far easier (to code and to understand). The max characters size a std::string (defined in header string ) can contain is std::npos , which is the max number you can have for the type std::size_t (usually a typedef for unsigned int ). Basically, you don't have to worry about a std::string max length.

std::string ch = "HelloWorld", ret;
auto ret_max_length = 20;

auto n_blanks = ret_max_length - ch.size();

// insert blanks at the beginning
ret.append(n_blanks / 2, ' ');

// append ch
ret += ch;

// insert blanks after ch
// if odd, simply add 1 to the number of blanks
ret.append(n_blanks / 2 + n_blanks % 2, ' ');

The approach I took here is different, as you can see.

Notice that, because of '\0' , the result of these two methods are NOT the same. If you want to obtain the same behaviour, you may either add 1 to DIM or subtract 1 from ret_max_length .

Assuming that we know the size, s, of the array, ret and knowing that the last character of any char array is '\0' , we find the length, l, of the input char array, ch.

int l = 0;
int i;
for(i=0; ch[i]!='\0'; i++){

 l++;

}

Then we compute how many spaces we need on either side. If total_space is even, then there are equal spaces on either side. Otherwise, we can choose which side will have the extra space, in this case, the left side.

int total_spaces = size-l-1; // subtract by 1 to adjust for '\0' character
int spaces_right = 0, spaces_left = 0;
if((total_spaces%2) == 0){

 spaces_left = total_spaces/2;
 spaces_right = total_spaces/2;

}
else{

 spaces_left = total_spaces/2;
 spaces_right = (total_spaces/2)+1;

}

Then first add the left_spaces, then the input array, ch, and then the right_spaces to ret.

i=0;
while(spaces_left > 0){

 ret[i] = ' ';
 spaces_left--;
 i++;

} // add spaces
ret[i] = '\0';

strcat(ret, ch); // concatenate ch to ret

while(spaces_right){

 ret[i] = ' ';
 spaces_right--;
 i++;

}
ret[i] = '\0';

Make sure to include <cstring> to use strcat() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM