2010-02-27 727 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

相關問題