Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check string start in C++

Tags:

c++

string

Is there any way in C++ to check whether a string starts with a certain string (smaller than the original) ? Just like we can do in Java

bigString.startswith(smallString); 
like image 779
sufyan siddique Avatar asked Nov 11 '11 14:11

sufyan siddique


People also ask

Can you index a string in C?

The index() function locates the first occurrence of c (converted to an unsigned char) in the string pointed to by string. The character c can be the NULL character (\0); the ending NULL is included in the search. The string argument to the function must contain a NULL character (\0) marking the end of the string.

How do you check the starting and ending point of a string?

In order to test the beginning and ending of a given string in Python, one can use the methods str. startswith() and str. endswith() .

How do I find a word in a string in C?

Search for a character in a string - strchr & strrchr The strchr function returns the first occurrence of a character within a string. The strrchr returns the last occurrence of a character within a string. They return a character pointer to the character found, or NULL pointer if the character is not found.

How do you check if a string begins with a letter?

The startsWith() method checks whether a string starts with the specified character(s). Tip: Use the endsWith() method to check whether a string ends with the specified character(s).


2 Answers

std::string s("Hello world");  if (s.find("Hello") == 0) {     std::cout << "String starts with Hello\n"; } 
like image 72
Some programmer dude Avatar answered Sep 28 '22 00:09

Some programmer dude


You can do this with string::compare(), which offers various options for comparing all or parts of two strings. This version compares smallString with the appropriate size prefix of bigString (and works correctly if bigString is shorter than smallString):

bigString.compare(0, smallString.length(), smallString) == 0 

I tend to wrap this up in a free function called startsWith(), since otherwise it can look a bit mysterious.

UPDATE: C++20 is adding new starts_with and ends_with functions, so you will finally be able to write just bigString.starts_with(smallString).

like image 43
Alan Stokes Avatar answered Sep 28 '22 00:09

Alan Stokes