How do I find a substring from the string path "/user/desktop/abc/post/" using C/C++? I want to check if folder "abc" is present or not in that path.
Path is character pointer char *ptr = "/user/desktop/abc/post/";
Simple Approach: The idea is to run a loop from start to end and for every index in the given string check whether the sub-string can be formed from that index. This can be done by running a nested loop traversing the given string and in that loop running another loop checking for sub-string from every index.
You can extract a substring from a String using the substring() method of the String class to this method you need to pass the start and end indexes of the required substring.
Python String find() method returns the lowest index or first occurrence of the substring if it is found in a given string. If it is not found, then it returns -1. Parameters: sub: Substring that needs to be searched in the given string.
(Search String for Substring) In the C Programming Language, the strstr function searches within the string pointed to by s1 for the string pointed to by s2. It returns a pointer to the first occurrence in s1 of s2.
Use std::string
and find
.
std::string str = "/user/desktop/abc/post/";
bool exists = str.find("/abc/") != std::string::npos;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With