我对C ++相当陌生,因此对于某些人来说,我所遇到的问题的答案似乎很明显。 我要实现的是创建一个方法,该方法将返回给定的char数组填充,该填充前后均需留有空格,以满足特定长度。因此,最后的效果就像给定的char数组位于另一个更大的char数组的中间。
可以说我们在HelloWorld中有一个char数组! 我希望该方法向我返回一个新的char数组,该数组具有预先指定的长度,并且给定的char数组“位于”返回的char数组的中间。
ListOfImages <- lapply(FilesToRead, FUN = load.image)
在给定char数组为奇数的情况下,它希望位于中间左侧一个空格的偏移量中。 我还想避免任何占用内存的字符串或标准库中没有的其他任何方法-使其尽可能简单。 解决这个问题的最佳方法是什么?谢谢!
答案 0 :(得分:2)
主要有两种方法:要么像使用C语言那样使用char文字(也就是char数组),要么使用内置的std::string
类型(或类似类型),这很常见。尽管有例外,但是如果您使用C ++进行编程,则可以选择。
我为您提供一个示例。
首先,使用数组时,您将需要包含cstring
标头才能使用内置的字符串文字操作功能。请记住,作为其长度的一部分,char数组始终以空终止符'\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
(在标题string
中定义)可以包含的最大字符数为std::npos
,这是类型std::size_t
(通常为{{ 1}}代表typedef
)。基本上,您不必担心unsigned int
的最大长度。
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
减1。
答案 1 :(得分:1)
假设我们知道数组ret的大小s,并且知道任何char数组的最后一个字符是'\0'
,我们就会找到输入char数组ch的长度l。 / p>
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,然后添加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()
。