1

I'm new to C++, learning from books and online video tutorials. I've been trying to get the following lines of code to work, without much success. Basically, trying to find a C++ equivalent to python'a .startswith() or "in".

In python, what I'm trying to achieve would look like this:

names = ["John","Mary","Joanne","David"]
for n in names:
   if n.startswith("J"):
      print(n)

In javascript, the syntax would be quite similar (there are better ways of doing this, but I'm trying to keep the lines of code close to python's):

const names = ["John","Mary","Joanne","David"];
for (let n of names) {
   if (n.startsWith("J")) {
      console.log(n);
}

So, I assumed things would work similarly in C++, right?

vector <string> names {"John","Mary","Joanne","David"};
for (auto n: names) {
   if (n[0] == "J") {
      cout << n << endl;
}

As I've just started learning about pointers, I might be getting confused between types / values / addresses, apologies for this.

What's the best way to solve this please? Alternatively, how should I find a way to mimic what "in" does in python, but for C++?

names = ["John","Mary","Joanne","David"]
for n in names:
   if "J" in n:
      print(n)

Thanks!

Louloumonkey
  • 59
  • 1
  • 6
  • Maybe `find` or `find_first_of`? – jtbandes Aug 20 '21 at 22:16
  • 1
    https://stackoverflow.com/questions/1878001/how-do-i-check-if-a-c-stdstring-starts-with-a-certain-string-and-convert-a – Vlad Feinstein Aug 20 '21 at 22:17
  • 2
    if you have c++20, there is [`std::string::starts_with`](https://en.cppreference.com/w/cpp/string/basic_string/starts_with) and in c++23 there will be [`std::string::contains`](https://en.cppreference.com/w/cpp/string/basic_string/contains). For such things you need some reference, nobody can remember all methods and functions. This is a good one: https://en.cppreference.com/w/cpp/string/basic_string. Actually I also only got to know about those two by browsing this list – 463035818_is_not_an_ai Aug 20 '21 at 22:32

0 Answers0