2010-06-30 14 views

risposta

28

Simile a this question:

CString str = _T("one+two+three+four"); 

int nTokenPos = 0; 
CString strToken = str.Tokenize(_T("+"), nTokenPos); 

while (!strToken.IsEmpty()) 
{ 
    // do something with strToken 
    // .... 
    strToken = str.Tokenize(_T("+"), nTokenPos); 
} 
+0

Ciao, Tokenize non è supportato in VC6 MFC, ma supportato in ATL – Dharma

+0

Si dovrebbe probabilmente aggiungere tale requisito alla domanda. – sje397

+4

[I documenti per CStringT :: Tokenize()] (http://msdn.microsoft.com/en-us/library/k4ftfkd2.aspx) dicono che la funzione salta i delimitatori iniziali, quindi se si vuole veramente dividere una stringa e non ignorare sottostringhe vuote, quindi direi che non puoi usare 'Tokenize()'. Ad esempio, "+ uno + due + tre + quattro" non darebbe il risultato previsto di 5 sottostringhe. – herzbube

7

In VC6, dove CString non ha un metodo Tokenize, si può rinviare alla funzione strtok Ed è amici.

#include <tchar.h> 

// ... 

CString cstr = _T("one+two+three+four"); 
TCHAR * str = (LPCTSTR)cstr; 
TCHAR * pch = _tcstok (str,_T("+")); 
while (pch != NULL) 
{ 
    // do something with token in pch 
    // 
    pch = _tcstok (NULL, _T("+")); 
} 

// ... 
18
CString sInput="one+two+three"; 
CString sToken=_T(""); 
int i = 0; // substring index to extract 
while (AfxExtractSubString(sToken, sInput, i,'+')) 
{ 
    //.. 
    //work with sToken 
    //.. 
    i++; 
} 

AfxExtractSubString on MSDN.

+2

Questo è un problema con OO scadente e API scadenti - funzioni dappertutto :) Buona scoperta. – sje397

+6

Puoi rispondere alla tua stessa domanda. È nelle FAQ. – sje397

+1

Vorrei cambiare il separatore di virgola in un segno più, altrimenti l'esempio non funzionerà. – TechNyquist

7
int i = 0; 
CStringArray saItems; 
for(CString sItem = sFrom.Tokenize(" ",i); i >= 0; sItem = sFrom.Tokenize(" ",i)) 
{ 
    saItems.Add(sItem); 
}