2017-10-29 126 views
1

假設我有一串二進制數字,例如。 1110001110010101,我想將這個數字存儲在一個字符串中。在二進制串的數字之間給出空間

現在我想分開這些1和0,以便我可以處理它們。我該怎麼做?

+2

的可能的複製[?我如何把一個空間,在這個輸出每四個字符之間(https://stackoverflow.com/questions/26302820/how-do- I-放-A-空間在其間-每四字符功能於該輸出) –

回答

2

當你與++的字符串存儲在列C上工作,使用索引可以訪問或使用迭代器

string str = "mystring"; 
  
   // Declaring iterator 
    std::string::iterator it; 

    // Declaring reverse iterator 
    std::string::reverse_iterator it1; 

    // Displaying string 
    cout << "The string using forward iterators is : "; 
    for (it=str.begin(); it!=str.end(); it++) 
    cout << *it; 

    cout << endl; 


    // Displaying reverse string 
    cout << "The reverse string using reverse iterators is : "; 

    for (it1=str.rbegin(); it1!=str.rend(); it1++) 
    cout << *it1; 
1

您可以隨時去的簡單方法,分配一個新的字符串(幾乎)是輸入字符串大小的兩倍,並且一次填充一個字符。

例如:

std::string expand(const std::string& str) 
{ 
    std::string new_str; 

    size_t size = str.size(); 
    new_str.resize(size*2-1); 

    for (size_t n = 0; n < size-1; n++) 
    { 
     new_str[n*2+0] = str[n]; 
     new_str[n*2+1] = ' '; 
    } 

    new_str[size*2-2] = str[size-1]; 

    return new_str; 
} 
相關問題