如何将字符串拆分为特定长度的子单元并将值存储为向量

时间:2017-09-10 08:05:40

标签: c++ substr

Split string using loop to specific length sub-units

string str("0123456789asdf");

for (unsigned i = 0; i < str.length(); i += 4) {
    cout << str.substr(i, 4) << endl;
}

所以我发现这个页面几乎是我想要的,但是我不需要打印值,而是需要将它们存储为矢量,这段代码给出了“0123”“4567”“89as”“df”,但是我需要将它们存储在一个向量中,因为最后一个元素是“df”我需要再附加2个“2”以使其成为“df22”(即如果所需的长度是5那么它应该是“01234”“56789 “”asdf1“因为5-4 = 1),有没有办法做到这一点?

2 个答案:

答案 0 :(得分:-1)

以下代码:

Sub Createfilter()

Dim cmd As ADODB.Command
Dim conn As ADODB.Connection
Dim strConn As String
Dim par As ADODB.Parameter           'input

strConn = "DRIVER=SQL Server;SERVER=CHU-AS-0004;DATABASE=RTC_LaplaceD_DEV;Trusted_Connection=Yes;"

Set conn = New ADODB.Connection
conn.Open strConn               'open connection


Dim rs As ADODB.Recordset
Dim introw
Dim strState As String
Dim str As String
Dim str1 As String
Dim str2 As String
Dim str3 As String
Dim str4 As String
Dim andboolean As Boolean 'decide to add "AND" to the sql string or not

andboolean = False 'initialze
Set rs = New ADODB.Recordset

str = "SELECT * FROM dbo.PilotRequest WHERE"
' RequestID
    str1 = " RequestID Like '"
    If IsNull(Filter1.value) Then str2 = "" Else str2 = Filter1.value
    str3 = "%' "
    str4 = str & str1 & str2 & str3
    MsgBox ("Str4" & str4)

    rs.Open str4, conn

    conn.Close
    Set rs = Nothing
    Set conn = Nothing

If str = "SELECT * FROM dbo.PilotRequest WHERE" Then
    str = "SELECT * FROM dbo.PilotRequest ORDER BY dbo.PilotRequest.RequestID DESC"
End If

ListRequest.RowSource = str4


ListRequest.Requery

End Sub

答案 1 :(得分:-2)

string str("0123456789asdff");
vector<string> strings;
int desire_length = 5;

int ss = str.length()/desire_length;

for (unsigned i = 0; i < str.length(); i += desire_length) {
    strings.push_back(str.substr(i, desire_length));
}

int c_no = desire_length - strings[ss].length();

if(str.length()%desire_length != 0){
    for(int i = 0; i<c_no; i++){
        strings[ss] += std::to_string(c_no);
    }
}

to_string()函数是在C ++ 11中引入的。