The direct answer to your question is probably using std::string::compare
or std::string::find
; I suppose a google search with terms "c++ string start with" would have brought you directly to examples with advantages and disadvantages.
However, when writing very simple parsers, the tokenizer strtok
from c's string library might me an easier way. strtok
subsequently splits a string into tokens, where each call to strtok
returns the next token. Characters separating tokens are passed as parameter to strtok
:
#include <iostream>
#include<stdio.h>
#include <stdlib.h>
int main()
{
std::string str = "type(a)";
if (str.compare(0,5,"type(") == 0) {
// string starts exactly with `type(`;
// note: 'type (' would not match...
}
char* analyzeStr = strdup(str.c_str());
char *token = strtok(analyzeStr, "(");
if (token && strncmp(token, "type", strlen("type")) == 0) {
// command starts with "type(" or "type ("
token = strtok(NULL, ")");
if (token) {
// value between brackets
printf("analyzing type of '%s'", token);
}
}
free(analyzeStr);
return 0;
}