簡體   English   中英

如何在文本的左側和右側用空格填充字符數組

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

我對 C++ 相當陌生,所以對於某些人來說,我的問題的答案似乎很明顯。 我想要實現的是創建一個方法,該方法將返回給定的 char 數組,並在其前后填充空格以滿足一定的長度。 所以最后的效果就像給定的 char 數組會在另一個更大的 char 數組的中間。

假設我們有一個帶有 HelloWorld 的 char 數組。 我希望該方法返回一個新的字符數組,該數組具有預先指定的長度,並且給定的字符數組“定位”在返回字符數組的中間。

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

如果給定的字符數組為奇數,則希望它位於中間左側一個空格的偏移量中。 我還想避免任何 memory 使用字符串或任何其他不在標准庫中的方法 - 盡可能保持簡單。 解決這個問題的最佳方法是什么? 謝謝!

主要有兩種方法:要么使用 char 文字(又名 char 數組),就像你在 C 語言中所做的那樣,要么使用內置的std::string類型(或類似類型),如果你'在 C++ 中重新編程,盡管有例外。 我為每個人提供一個例子。

首先,使用 arrays,您需要包含cstring header 以使用內置的字符串文字操作函數。 請記住,作為長度的一部分,char 數組始終以 null 終止符'\0' (ASCII 碼為 0)終止,因此對於DIM維度的字符串,您將能夠將字符存儲在DIM - 1位置。 這是帶有注釋的代碼。

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) = ' ';

我選擇首先在字符串的開頭和結尾插入空格,然后復制ch的內容。

第二種方法要容易得多(編碼和理解)。 std::string (在 header string中定義)可以包含的最大字符大小是std::npos ,這是std::size_t類型(通常是unsigned inttypedef )可以擁有的最大字符數。 基本上,您不必擔心std::string最大長度。

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, ' ');

如您所見,我在這里采用的方法有所不同。

請注意,由於'\0' ,這兩種方法的結果不同。 如果您想獲得相同的行為,您可以將 1 添加到DIM或從ret_max_length中減去 1。

假設我們知道數組 ret 的大小 s 並且知道任何 char 數組的最后一個字符是'\0' ,我們找到輸入 char 數組 ch 的長度 l。

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

 l++;

}

然后我們計算兩邊需要多少空間。 如果 total_space 是偶數,則兩邊的空格相等。 否則,我們可以選擇哪一側有額外的空間,在這種情況下,左側。

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;

}

然后首先添加 left_spaces,然后是輸入數組 ch,然后是要 ret 的 right_spaces。

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';

確保包含<cstring>以使用strcat()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM