vendredi 20 août 2021

How to approach .startswith() in C++? [duplicate]

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!

Aucun commentaire:

Enregistrer un commentaire