For example, you want to compare s1 == s2(0, 10), which means the first ten characters of string s2, use substr() may work it through, like this :
s1 == s2.substr(0, 10);
in which, s2.substr(pos, n) mean the continuous n characters begin with the pos-th position of string s2.
Another funtion is also goot to use :
s1.compare(pos1, n1, s2);
menas: compare the n1 characters begin from pos1 position of string s1, to string 2. You can checkout this funtion and its overloaded other five funtions.
Answer from smh on Stack OverflowFor example, you want to compare s1 == s2(0, 10), which means the first ten characters of string s2, use substr() may work it through, like this :
s1 == s2.substr(0, 10);
in which, s2.substr(pos, n) mean the continuous n characters begin with the pos-th position of string s2.
Another funtion is also goot to use :
s1.compare(pos1, n1, s2);
menas: compare the n1 characters begin from pos1 position of string s1, to string 2. You can checkout this funtion and its overloaded other five funtions.
To do this in-place, just use std::strncmp(). For example:
bool first_n_equal(const char *lhs, const char *rhs, size_t n) {
return (std::strncmp(lhs, rhs, n) == 0);
}
Note that strncmp returns 0 if the two strings are equal, and will only compare up to n characters. To pick n you can hardcode 6, or loop over your string and check for where the first word ends. For example,
size_t size_of_first_word(const char *str) {
size_t i;
for (i = 0; str[i] != ' ' && str[i] != '\0'; i++) {}
return i;
}
This function loops over the string until it hits a space or a null terminator (end of string). Then, to actually check your string for a command:
size_t input_len = size_of_first_word(input_string);
size_t command_len = size_of_first_word(command_string);
size_t check_len = std::min(input_len, command_len);
bool is_same = first_n_equal(input_string, command_string, check_len);
I intentionally made this verbose to make it easier to understand, so you can absolutely make this code smaller. You could also use std::string but it's not actually necessary.
Don't have access to a compiler, but I think this will work because C-style strings are just arrays with a termination character:
int isAbsolute(const char *str){
return (str[0] == '/');
}
strcmp compares the whole string, so your function will only return true if the string you're passing is "/".
You can look at strncmp instead:
if(strncmp(str,"/", 1)) ...
or compare only one character:
(if (str[0] == '/')) ...