2010-02-27 124 views
1

我有一个字符串,我想将其复制到固定长度的字符串中。例如,我有一个长度为16个字符的string s = "this is a string"如何将字符串复制到C++中的固定长度字符串中

我想复制到一个固定长度的字符串s2这是4个字符长。所以s2将包含"this"

我也想把它复制成长度为20个字符的固定长度字符串s3。由于原始字符串只有16个字符,因此字符串的末尾会有多余的空格。

+1

你认为什么是“固定长度字符串”?像C中的字符数组? – sbi 2010-02-27 10:43:34

+3

为什么不指定disired接口(和使用示例),以便答案可以提供实现? – mlvljr 2010-02-27 11:25:33

+0

字符数组是固定长度字符串的示例。 – neuromancer 2010-02-27 13:38:10

回答

6
s.resize(expected_size,' '); 
+0

+1:您的解决方案是最干净的 – Vlad 2010-02-27 12:02:24

+0

+1,'std :: string(orig_s).resize(expected_size,'')'? :)) – mlvljr 2010-02-27 15:37:21

3

如果您使用的std :: string,看substr复制字符串的第一部分,构造string(const char *s, size_t n)创建长度为n与内容s(重复)和replace更换的零件串你的空弦,这些会为你做这项工作。

1

substrresize/replace会做你想要什么:

#include <string> 
#include <iostream> 
using namespace std; 

int main() 
{ 
    string s = "abcdabcdabcdabcd"; 
    string t; 
    string u; 

    t = s.substr(0,4); 
    u = s; 
    u.resize(20, ' '); 

    string v(20, ' '); 
    v.replace(0, s.length(), s); 

    cout << "(" << s << ")" << endl 
     << "(" << t << ")" << endl 
     << "(" << u << ")" << endl 
     << "(" << v << ")" << endl; 
}  
1

如果你想要的东西可重用的,你可以写几个辅助函数:

// Non-mutating version of string::resize 
std::string resize_copy(std::string const & str, std::size_t new_sz) 
{ 
    std::string copy = str; 
    copy.resize(new_sz); 
    return copy; 
} 

void resize_to(std::string const & str, std::string & dest) 
{ 
    dest = resize_copy(str, dest.size()); 
} 

int main() 
{ 
    std::string a = "this is a string"; 
    std::string b(4, ' '); 
    std::string c(20, ' '); 
    resize_to(a, b); 
    resize_to(a, c); 
    std::cout << b << "|\n" << c << "|\n"; 
} 

此打印:

this| 
this is a string | 
0

对于以空字符结尾的字符串,您可以使用sprintf

例子:

char* s1 = "this is a string"; 
    char s2[10]; 
    int s2_size = 4; 
    sprintf(s2, "%-*.*s", s2_size, s2_size, s1); 
    printf("%s\n", s2); 

%-*.*s格式说明调整字符串的大小,并添加额外的空格,如果它是必要的。

-1

要在C++中处理固定长度的字符串,请使用C库函数,如strncpy

+0

为什么要投票?另外,固定长度的字符串没有最终的'\ 0',在这种情况下使用抽象技术是一种矫枉过正的行为。 – Spidey 2013-08-14 19:26:51

相关问题