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

f.bele

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!

Ojd2000

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.

Este artigo é coletado da Internet.

Se houver alguma infração, entre em [email protected] Delete.

editar em
0

deixe-me dizer algumas palavras

0comentários
loginDepois de participar da revisão

Artigos relacionados

iOS Swift how to make textview/label on left hand side of a view and if there are too many text, it goes under the right view

How to right pad a field with spaces using AWK

printf int to char array with left padded spaces

Error with <string>.append() in ton-solidity: Different number of components on the left hand side (1) than on the right hand side (0)

How to pad a 2d array with variable length per row on the left and right to form a bigger 2d array

How to display close button on the right hand side in the Tab

How to align Material Design Lite cards to right hand side

How to make a bootstrap carousel with a caption on the right hand side?

show the content on the right hand side

How do i make the left and right side of the border get closer to the text

right pad regex with spaces using sed or awk

How to indent text from the right side?

Nullish coalescing operator (??) with right hand side 'undefined'

Use "at variable" ($@) on the right hand side of a rule in makefile

Right hand side position of substring MySQL

Rewrite sympy equations to 0 right hand side

Using metric in right hand side of prometheus query

Buffer filling last empty spaces in char array with unwanted data

How to place an element at the left and right side of overflowing div

Python - Formatting So When Text is Printed It Appears From the Right Side Not Left Side

How to call a concatenated vector of variable names in the right-hand side of a formula?

How to show the imageview in right hand side edge(i.e) before the logout icon?

How to fix "TypeError: Right-hand side of 'instanceof' is not callable" when I use another module class?

How to add an histogram or density plot on the right hand side of this example plot to describe the distribution of y-values?

How do I add a prefix to the right hand side of a Formula using update?

How do I limit draggable area? it functions on top and left side, but not on the right side and bottom

How to move dropdown arrow left side instead of right side which is by default in flutter?

clear empty spaces array

How can I set Angular 6 Material sidenav to open right to left from the right side of the screen

TOP lista

  1. 1

    R Shiny: use HTML em funções (como textInput, checkboxGroupInput)

  2. 2

    O Chromium e o Firefox exibem as cores de maneira diferente e não sei qual deles está fazendo certo

  3. 3

    Como assinar digitalmente um documento PDF com assinatura e texto visíveis usando Java

  4. 4

    R Folheto. Dados de pontos de grupo em células para resumir muitos pontos de dados

  5. 5

    Gerenciar recurso shake de Windows Aero com barra de título personalizado

  6. 6

    Como obter dados API adequados para o aplicativo angular?

  7. 7

    UITextView não está exibindo texto longo

  8. 8

    Por que meus intervalos de confiança de 95% da minha regressão multivariada estão sendo plotados como uma linha de loess?

  9. 9

    Acessando relatório de campanhas na AdMob usando a API do Adsense

  10. 10

    Usando o plug-in Platform.js do Google

  11. 11

    Como posso modificar esse algoritmo de linha de visada para aceitar raios que passam pelos cantos?

  12. 12

    Dependência circular de diálogo personalizado

  13. 13

    Coloque uma caixa de texto HTML em uma imagem em uma posição fixa para site para desktop e celular

  14. 14

    iOS: como adicionar sombra projetada e sombra de traço no UIView?

  15. 15

    Como usar a caixa de diálogo de seleção de nomes com VBA para enviar e-mail para mais de um destinatário?

  16. 16

    Tabela CSS: barra de rolagem para a primeira coluna e largura automática para a coluna restante

  17. 17

    How to create dynamic navigation menu select from database using Codeigniter?

  18. 18

    Converter valores de linha SQL em colunas

  19. 19

    ChartJS, várias linhas no rótulo do gráfico de barras

  20. 20

    用@StyleableRes注释的getStyledAttributes。禁止警告

  21. 21

    não é possível adicionar dependência para com.google.android.gms.tasks.OnSuccessListener

quentelabel

Arquivo