Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

CString::Find Question

Status
Not open for further replies.

fdsouth

Technical User
Jun 6, 2001
61
US
CString::Find is useful for locating a single character within a string but how would one use it (if possible) to find the location of a "sub-string" within a longer string. For example, lets say I have a text file containing the string "19mm". Can I still use the Find function to point to where it begins? If not, any suggestions?
 
find should be able to search for a string as well

CString::Find(LPCTSTR)const BUT i dont think there is a case-insensitive version. For that I would make 2 CStrings

CString str1(origString);
CString str2(searchString);

str1.MakeUpper();
str2.MakeUpper();

int idx = str1.Find(str2);

Matt


 
I worked on the problem a little before I got you response. I came up with the following:

Code:
ifstream InputFile("z:\\angles", ios::in);
while(!InputFile.eof())
{
   InputFile.getline(buffer.GetBuffer(256),256, '\n');
   int index = buffer.Find("19mm",0);
   if( index != -1)
   {
	MessageBox(buffer.Mid(index,2));
   }
   buffer.ReleaseBuffer();
}

I though that this would read in a line of 256 characters (or until a newline is encountered), place the data into a CString named buffer, then find whether or not the string "19mm" was present. If so, the string "19" would be output in a message box. It seems to work except that only "1" is output to a message box. I'm sure it's something obvious that I'm missing.
 
No... that looks good to me.


in the if conditional try this before the MessageBox

CString temp(buffer.Mid(index,2);
MessageBox(temp);

or set a break point at temp and verify that it is being set to "19"

matt
 
I still can't get it to output "19". I set a breakpoint and checked everything. The index value was correctly set to 1. (The string generated from the getline is " 19mm bar stock")
However, when I used the CString::Mid function as stated above to output the characters at buffer[index] (for "1") and buffer[index+1] (for "9"), no luck.

Further, I created two CStrings to capture the characters separately. One for buffer[index] which should return "1" , it did, and another buffer[index+1] to return "9", it didn't. I get an empty CString. Any thoughts?
 
I still don't understand why I can't get it to work, but there's no need to keep messing with it. This gives me the same result:

Code:
InputFile.getline(buffer.GetBuffer(256),256);
if(buffer.Find("19mm",0) != -1)
{
	MessageBox("19");
}

Thanks for your help
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top