Searching CStrings in C++ - c++

I was wondering if there is a native C++ (or STL/Boost) function which will search a CString for a specified string?
e.g.
CString strIn = "Test number 1";
CString strQuery = "num";
bool fRet = SomeFn(strIn, StrQuery);
if( fRet == true )
{
// Ok strQuery was found in strIn
...
I have found a small number of functions like CompareNoCase IndexOf etc... but so far they don't really do what I want them to do (or use CLR/.Net)
Thanks!

CString::Find() is what you want, one of the overloads does sub-string searching.
CString strIn = "test number 1";
int index = strIn.Find("num");
if (index != -1)
// ok, found

string::find

Have you tried CString::Find?
It's not STL or boost but since you have two CString's it seems the most reasonable method to use.

Related

How to get letter from String by index? C++

Can someone briefly explain how to get a character from index from String in C++.
I need to read the first 3 letters of a String and in java it would bestr.charAt(index) and I have been searching the internet for a solution for 2h now and still don't understand...
can some one please give me an example.
std::string provides operator[] to access a character by index:
https://en.cppreference.com/w/cpp/string/basic_string/operator_at
Example:
const std::string s("hello");
const char c = s[0];
// c is set to ‘h’
substr()
It returns a newly constructed string object with its value initialized to a copy of a substring of this object.
Syntax
substr(pos, pos+len)
Code
std::string str ("Test string"); //string declaration
string sub_string = str.substr(0,3);
String index starts from 0.
Best place to look would be cpluspluc.com: http://www.cplusplus.com/reference/string/string/
You may use as earlier mentioned: http://www.cplusplus.com/reference/string/string/operator[]/
std::string str ("Test string");
for (int i=0; i<str.length(); ++i)
{
std::cout << str[i];
}
Or better yet: http://www.cplusplus.com/reference/string/string/at/
std::cout << str.at(i);
which also checks for a valid position and throws an out of range exception otherwise.
Alternatively you could use http://www.cplusplus.com/reference/string/string/data/
to acces the raw data.
Or if you want to check that your string starts with a specific pattern: http://www.cplusplus.com/reference/string/string/rfind/
std::string str = "Hey Jude!";
if (str.rfind("Hey", 0) == 0) {
// match
}
Another option to obtain a single character is to use the std::string::at() member function. To obtain a substring of a certain length, use the std::string::substr member function.

C++ - grep path in linux

I am new to linux and I want to know how to get path which is in the following format - /home/linux/sample/?
I want to write a c++ function which takes the path as input and returns true as if the path has /home/linux/sample/.
Example:
If the path is /home/linux/sample/test.txt should return true
If the path is /home/linux/sample/dir should return true
If the path is /home/linux/user/test.txt should return false
Can some one please help me?
Thanks in advance.
To write such a function you need only std::string:
string str ("There are two needles in this haystack.");
string str2 ("needle");
if (str.find(str2) != string::npos) {
//.. found.
}
If the algorithm will get more sophisticated than I would move to regular expressions.
Looks like you're trying to check if a string is the prefix of another one. In that case, you can rely on std::equal from <algorithm>:
std::string prefix = "/home/linux/sample/";
std::string path0 = "/home/linux/sample/test.txt";
if(std::equal(prefix.begin(), prefix.end(), path0.begin())) {
...
}
The / at the end of prefix is important!

check if a pointer has some string c++

I am not good with c++ and I cannot find this anywhere, please apologize me if it is a bad question. I have a pointer and I want to know if some names store in this pointer begins with some specific string. As in python something like (maybe it is a bad example):
if 'Pre' in pointer_name:
This is what I have:
double t = 0;
for (size_t i =0; i < modules_.size(); ++i){
if(module_[i].name() == "pre"){ // here is what I want to introduce the condition
if (modules_[i].status() == 2){
std::cout << module_[i].name() << "exists" << std::endl;
}
}
}
The equivalent of Python 'Pre' in string_name is:
string_name.find("Pre") != std::string::npos // if using string
std::strstr(pointer_name, "Pre") // if using char*
The equivalent of Python string_name.startswith('Pre') ("begins with some specific string") is:
string_name.size() >= 3 && std::equal(string_name.begin(), string_name.begin() + 3, "Pre"); // if using string
string_name.find("Pre") == 0 // less efficient when it misses, but shorter
std::strncmp(pointer_name, "Pre", 3) == 0 // if using char*
In two of those cases, in practice, you might want to avoid using a literal 3 by measuring the string you're searching for.
Check std::string::find, there are enough good examples. If you are using c-style string, use strstr.
You can use the algorithm header file to do most of things usually one liners in python.
In this case though it might be just easier to use string find method .
If your name variable is of type std::string then you can use name().compare("Pre") == 0 for string comparison.
EDIT: Seems I misunderstood the question, for contains you can use string find, as other said.
Using C style strings, char * is not recommended in C++. They are error prone.

How can I access a string like an array in AutoIt? (I'm porting code from C++ to AutoIt)

Ok, gah, syntax conversion issue here...How would I do this in AutoIt?
String theStr = "Here is a string";
String theNewStr = "";
for ( int theCount = 0; theCount < theStr.Size(); theCount++ )
{
theNewStr.Append(theStr[theCount]);
}
I am trying to access individual chars within a string in AutoIt and extract them. Thats's it. Thanks.
What about this:
$theStr = StringSplit("Here is a string", "") ; Create an array
$theNewStr = ""
For $i = 1 to $theStr[0] Step 1
$theNewStr = $theNewStr & $theStr[$i]
Next
MsgBox(0, "Result", $theNewStr)
#include <string>
std::string theStr = "Here is a string";
std::string theNewStr;
//don't need to assign blank string, already blank on create
for (size_t theCount = 0; theCount < theStr.Size(); theCount++ )
{
theNewStr += theStr[theCount];
}
//or you could just do
//theNewStr=theStr;
//instead of all the above
in autoit, it's just as simple to copy a string. to access a piece of a string (including a character, which is still a string) you use StringMid() which is a holdover from Microsoft BASIC-80 and now Visual BASIC (and all BASICs). you can stil do
theNewStr = theStr
or you can do it the hard way:
For $theCount = 1 to StringLen($theStr)
theNewStr &= StringMid($theStr, $theCount, 1)
Next
;Arrays and strings are 1-based (well arrays some of the time unfortunately).
& is concatenation in autoit. stringmid extracts a chunk of a string. it MIGHT also allow you to do the reverse: replace a chunk of a string with something else. but I would do unit testing with that. I think that works in BASIC, but not sure about autoit.

CString extract file path

Hey I'm trying to extract the file path but the problem is that I'm stuck in an infinite loop don't understand why. Please have a look at my code.
CString myString(_T("C:\\Documents and Settings\\admin\\Desktop\\Elite\\Elite\\IvrEngine\\dxxxB1C1.log"));
int pos = myString.Find(_T("\\"));
while (pos != -1)
{
pos = myString.Find(_T("\\"), pos); // it keeps returning 2
}
CString folderPath = myString.Mid(pos);
Now the problem is that, Find() returns 2 the first time I run, but then in the while loop it keeps returning 2, why is the function unable to find the rest '\' ? So now I'm in an infinite loop :(.
It sounds like Find includes the character at the position you give it when searching. So if you give it the position of a character that matches the search, then it will return that same position.
You probably need to change it to:
pos = myString.Find(_T("\\"), pos + 1);
your code will never work! When the while loop finished, the contend of pos can not be used.
Here is a solution which will work:
CString folderPath;
int pos = myString.ReverseFind('\\');
if (pos != -1)
{
folderPath = myString.Left(pos);
}
You can fix the code (see the pos + 1 answers) but I think that you should use _splitpath_s instead which was intended for this kind of operations.
CString::Find always returns the first occurence of the character you're searching for. So it keeps finding the the first "\\" which is at index 2 infinitely since you're searching from 2 which includes that "\\"
I can understand your initial implementation, as the behaviour of CString::Find() seem to have changed over time.
Take a look at the MSDN docs for MFC implementation shipped with VC6 here and at the current implementation here. Especially look at the differences of the description of the 2nd offset parameter.
The solution to your problem is, as already stated above, to add 1 to the search offset of the successive Find() calls. You can also search for single chars (or wchar_ts) like that:
myString.Find(_T('\\'), pos+1);
EDIT:
BTW, take a look at the Path* familly of functions exposed by the shlwapi.dll, declared in shlwapi.h. Especially the PathRemoveFileSpec function might be of interest to you.
in MFC, example to get folder which including executable file:
char ownPth[MAX_PATH];
// Will contain exe path
HMODULE hModule = GetModuleHandle(NULL);
if(NULL == hModule){
return __LINE__;
}
// When passing NULL to GetModuleHandle, it returns handle of exe itself
GetModuleFileName(hModule,ownPth, (sizeof(ownPth)));
modulePath = (LPCSTR)ownPth;
modulePath = modulePath.Left(modulePath.ReverseFind(_T('\\')));
return 0;