C++ - find function does not work executed on substring

program to find substring in a string in c++
find all occurrences of a substring in a string c++
find character in string c++
substr c++
npos - c++
find function in c
strstr
how to find a word in a string c++

I do have got a problem with an algorithm, which I want to use to split command line into several substrings. E.g. the string "Hello World -n filename" should be sliced into "Hello" "World" and "-n filename".

Here is my whole code example:

string hello = "Hello World -n filename";
uint64_t startIndex = 0;
uint64_t endIndex = hello.length() - 1;

while(startIndex < endIndex) {
    uint64_t nextWhiteSpaceIndex;
    string value;

    if(hello.at(startIndex) != '-') {

        nextWhiteSpaceIndex = hello.substr(startIndex).find(" ");
        value = hello.substr(startIndex, nextWhiteSpaceIndex);
        cout << value << endl;

    } else {

        nextWhiteSpaceIndex = hello.substr(hello.substr(startIndex).find(" ")).find(" ");
        value = hello.substr(startIndex, nextWhiteSpaceIndex);
        cout << value << endl;

    }
    startIndex = nextWhiteSpaceIndex + 1;
}

And I do have problems with this command:

nextWhiteSpaceIndex = hello.substr(startIndex).find(" ");

This is placed within the while-loop and it seems like the...

.substr(startIndex)

... part is completely ignored. The first loop run works fine, but during the second/following the nextWhiteSpaceIndex does not get the right next index assigned. It always prints "Hello" "World" "World" "World" "World" and continues to print "World".

Do you guys have a hint, why this does not work? I could not find an appropriate explanation during my research through the web.

hello is never changed, yet you're using find on only part of it (substr), and then calling substr(startIndex) on the whole string (hello) over and over again.

  1. "Hello World -n filename".find(" ") -> 5
  2. "World -n filename".find(" ") -> 5 again ("World" is the same length as "Hello")
  3. "World -n filename".find(" ") -> 5

You could use std::string::find's second argument (size_type pos) to specify the start offset where to start the search and create fewer temporary strings:

#include <iostream>

using namespace std;

int main() {
  const string hello = "Hello World -n filename";

  size_t startIndex = 0, pos = 0;
  bool eat = true;

  while(true) {
    pos = hello.find('\x20', pos);

    if(pos == string::npos) {
      cout << hello.substr(startIndex) << endl;
      break;
    }
    else if(eat && hello[startIndex] == '-') {
      eat = false;
      ++pos;
      continue;
    }

    cout << hello.substr(startIndex, pos - startIndex) << endl;

    startIndex = ++pos;
    eat = true;
  }

  return 0;
}

Output:

$ c++ main.cpp && ./a.out
Hello
World
-n filename

How to Find a Substring in a String with C++, How to find a substring inside a string in C++ using the find standard library function. As an example, in C++, if you have ever wondered how to determine if the is no reason this code should not also run in an environment with gcc find function to get the position of the first character of the substring in  In C++, std::substr() is a predefined function used for string handling. string.h is the header file required for string functions.. This function takes two values pos and len as an argument and returns a newly constructed string object with its value initialized to a copy of a sub-string of this object.

Can't you do something like

#include <sstream>
#include <stdio>
#include <vector>

using namespace std;

int main ()
{
    string hello = "Hello World -n filename";

    stringstream ss (hello);
    vector<string> v;
    string s, t;

    while (ss >> s)
    {
        if (s[0] == '-')
        {   
            ss >> t;
            v.push_back (s + " " + t); 
        }   
        else
            v.push_back (s);
    }

    for (auto i : v)
        clog << i << endl;

    return 0;
}

produces

$ ./a.out
Hello
World
-n filename

string::find - C++ Reference, string (1), size_t find (const string& str, size_t pos = 0) const;. c-string (2) If this is greater than the string length, the function never finds matches. Note: The first character is denoted by a value of 0 (not 1): A value of 0 means that Edit & Run​  The C library function char *strstr(const char *haystack, const char *needle) function finds the first occurrence of the substring needle in the string haystack. The terminating '\0' characters are not compared. Following is the declaration for strstr() function. This function returns a pointer to

If you output the value for nextWhiteSpaceIndex you will always see: 5, 5, 5, 5... It's an index relative to startIndex, so simply changing the last line into startIndex += nextWhiteSpaceIndex + 1; would probably quickfix the issue.

(Aren't you taking too many substrings? std::string::find can take the search start index as argument, so you can perform the whole search on always the same buffer.)

Programming and Problem Solving with C++, Below are some more examples of calls to the find function, assuming the following code segment has been executed: string strl; string str2; strl = "​Programming  The substring is the portion of the object that starts at character position pos and spans len characters (or until the end of the string, whichever comes first). Position of the first character to be copied as a substring. If this is equal to the string length, the function returns an empty string. If this is greater than the string length, it

string find in C++, String find is used to find the first occurrence of sub-string in the specified string The function returns the index of the first occurrence of sub-string, if the sub-string is not found it returns string::npos(string::pos is static member with CPP program to demonstrate working of string size_t find (const char c, size_t pos = 0);. Searches the string for the first occurrence of the sequence specified by its arguments. Notice that unlike member find_first_of, whenever more than one character is being searched for, it is not enough that just one of these characters match, but the entire sequence must match. Another string with the subject to search for.

Programming in C++, If strl and str2 are of type string, the following are valid function calls: strl. find If the substring could not be found, the function returns the special value to the find function, assuming the following code segment has been executed: string strl ; string str2: strl = "Programming and Problem Solving"; str2 = "gram"; |Function 94  If you have ever wondered how to find a substring inside another string in C++ then hopefully this tutorial will help walk you through how to do that. As an example, in C++, if you have ever wondered how to determine if the substring "Agnosticdev," is part of the parent string "Hello Agnosticdev, I love Tutorials," then this tutorial will show

strstr() in C/C++, In C++, std::strstr() is a predefined function used for string handling. string.h is Return Value: This function returns a pointer points to the first character of the found s2 in s1 otherwise a null pointer if s2 is not present Find first occurrence of s2 in s1 last_page Implementing own Hash Table with Open Addressing Linear  Since you only select the Student-row, and that contains an '@'-character in email you should be OK. But you're not, so I'm thinking the SUBSTRING-function might be executed **before** the FILTER-operation in the execution plan for the second query.

Comments
  • Did you use a debugger to inspect your code during runtime?
  • Yes, sure. After the first loop run every variable assignment is done correctly. When it comes to assign the nextWhiteSpaceIndex variable, it seems that the find() method is executed on the initial string and not the substring.
  • I really like your explanation and your solution. Now it is totally clear, where my error was located. Thanks, that helped to understand C++ a little bit more!