4

I mostly write my codes in java and have started using c++ too. I wanted to know how to check if a given string in c++ starts with another specified string. I have posted the equivalent code in java below.

public boolean check(String string) //ENTERED string
{
    String another_string="SSS"; //to be checked if the ENTERED string starts with this string

    return (string.startsWith(another_string)); //<string>.startsWith(<string>) returns a boolean value

}
Jose Luis
  • 3,307
  • 3
  • 36
  • 53
Piyush Ranjan
  • 329
  • 1
  • 4
  • 9
  • `std::equal` should do that without looking through the entire string like `.find` or something would if the substring doesn't exist in the string. – chris Oct 23 '14 at 11:52
  • can you please post and example explaining how to use std::equal? – Piyush Ranjan Oct 23 '14 at 12:05

1 Answers1

6

http://ideone.com/w1ifiJ

#include <iostream>
using namespace std;

int main() {
    string str ("abcdefghijklmnoabcde");
    string str2 ("abcde");

    size_t found = str.find(str2);

    if(found == 0)
    {
         cout << "found";
    }

    return 0;
  }

more info : http://www.cplusplus.com/reference/string/string/find/

utarid
  • 1,642
  • 4
  • 24
  • 38
  • please try to find string "bcde" and You can see, that it finds it, what is wrong result if we ask if it "starts with" string, not "contains" one. – Hunter_71 Jul 18 '18 at 23:45
  • 1
    if you read question, OP want to check if string start another known string not string contain another known string. find returns position and if position equals to 0 then you can understand string start with it. if you use bcde, find return 1 because bcde is in 1st position. so there is no problem with answer. – utarid Jul 19 '18 at 06:27
  • 1
    Yes, You have right, found == 0 is the answer to "starts with" :) Sorry, my bad. – Hunter_71 Jul 19 '18 at 22:29