0

I'm fairly new to coding, so i might be a bit slow.

so i have a CString of an equation that the user inputs, and i want to separate the numbers and operators so that they have their own indexes in a CStringArray.

So for example this is what i mean:

i have a string

CString str = "123 + 32 / 2"

i want the string into this...

CStringArray arr = ['123', '+' , '32' , '/' , '2']

how would i go about doing this?

i was thinking of using a for loop, and finding where there are spaces, and then 'grabbing' the number or operator out there, but i can't really wrap my head around how i can do that.

0

2 Answers 2

3

You can use the Tokenize() method of CString in order to split your string. Check the example in the msdn documentation : https://msdn.microsoft.com/en-us/library/k4ftfkd2.aspx Here is the code for your problem, it is the same than the one in the example with your data. You have to add resToken to your CStringArray in order to populate it.

CStringArray arr;
CString m_StoreEx = _T("123 + 32 / 2");
int curPos = 0;
CString resToken= m_StoreEx.Tokenize(_T(" "),curPos);
while (resToken != _T(""))
{
   _tprintf_s(_T("Resulting token: %s\n"), resToken);
   arr.Add(resToken);
   resToken = m_StoreEx.Tokenize(_T(" "), curPos);
};
2
  • i read the msdn documentation, my question now is, how so to manipulate the 'token'? like how to i use it? is a token like a variable? i just dont know how to add it to my array. i tried: ` CStringArray arr; int curPos = 0; CString resToken= m_StoreEx.Tokenize(_T(" "),curPos); while (resToken != _T("")) { //_tprintf_s(_T("Resulting token: %s\n"), resToken); resToken = m_StoreEx.Tokenize(_T(" "), curPos); arr.Add(resToken); ` does'y seem to work for me tho
    – Barcode
    Aug 5, 2015 at 8:49
  • m_StoreEx my CString variable that stores the string of equations btw
    – Barcode
    Aug 5, 2015 at 9:04
0
CString s = _T("123 + 32 / 2");
CStringArray sa;

int i = 0, j = 0;
while (-1 != (i = s.Find(' ', i))) {
    if (i != j)
        sa.Add(s.Mid(j, i - j));
    j = ++i;
}
sa.Add(s.Mid(j)); // Last one

You can put it into a helper function for further use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.