FunctionX Learning Logo

Strings Implementations

 
 

Replacing a String Occurrence

 

The CString class provides a mechanism for deleting an occurrence of a certain string in another string. The function for performing this is called Replace. The CString::Replace() function allows you to control the content of a string especially if you are getting the string from an unpredictable source.

Image the user is supposed to type a quadratic equation such as 3x^2+5. There are millions of ways the user can type it. The problem is that if you are planning on resolving the equation, before even getting to the solutions of the equation, you need to be able to "know" what the equation is made of; you cannot just try to retrieve a, b, and c. The user could type 3 x^2+ 5 or 3x ^2 +5 or 3 x ^ 2 + 5 or 3x ^2+ 5. As you can see, the possibilities are as numerous as imaginable. Remember that a string can consist of an empty space. Therefore, one of the first things you should perform is to remove any empty space in the equation. Eventually, you will use other functions to analyze the equation, find the parentheses if any, find the special characters such as ^ usually used to express the power in computer languages; you might also want to know if the user typed the equation in the form of Ax^2 + B = C.

  1. Create a dialog based application using MFC.
  2. Add an Edit Box control to the dialog. Change its identifier to IDC_EQUATION
  3. Add a Button control to the dialog. Change its identifier to IDC_BTN_REMOVESPC and its caption to &Remove Space. Resize the button to make sure the caption is completely visible.
  4. Press Ctrl + W to access the ClassWizard.
  5. On the MFC ClassWizard property sheet, click the Member Variables property page.
  6. Double-click IDC_EQUATION.
  7. Change the name of the variable to m_Equation and make sure its Category Value is CString then click OK.
  8. Click the MessageMaps property page.
  9. Create a function for the IDC_BTN_REMOVESPC button using the BN_CLICKED message. Rename the function OnRemoveSpace
  10. Implement the function as follows:
     
    Listing 1
    void CExoDialog1Dlg::OnRemoveSpace() 
    {
    	UpdateData();
    	m_Equation.Replace(" ", "");
    	UpdateData(FALSE);
    }
  11. To test the program, press Ctrl + F5

 

 
 

Home Copyright 2002-2005 FunctionX, Inc.