c++如何将大字符串放入固定字符数组

c++ how to put large string into fixed char array

本文关键字:字符 数组 字符串 c++      更新时间:2023-10-16

嘿,我有一个很长的字符串,我试图把它粘在一个固定大小的字符数组。我不在乎字符串是否被截断,我只希望字符数组的每个元素都有一些东西。

例如

char first_ten_alaphabet[10];
string str = "abcdefghijklnopqrstuvwxyz";

strcpy(first_ten_alaphabet, str.c_str());  //<-- this will cause program to break

任何帮助都很好,谢谢

如果你想复制(并可能截断)一个c风格的字符串,那么我会使用strncpy而不是"strcpy()"。

strncpy()的一个限制是,如果#/字符正好等于复制长度,它将而不是以null终止字符串。这是设计的结果,但如果你没有预料到,这是一个潜在的"陷阱"。只需添加第二个语句,在最后位置放置一个NULL字符:

char first_ten_alphabet[10];
string str = "abcdefghijklnopqrstuvwxyz";
strncpy(first_ten_alphabet, str.c_str(), sizeof(first_ten_alphabet));
first_ten_alphabet[sizeof(first_ten_alphabet)-1] = '';

use std:copy,http://www.cplusplus.com/reference/algorithm/copy/copy(str.begin(),str.begin()+sizeof(first_ten_alaphabet),first_ten_alaphabet);