Imagine that I have two strings, one of them is a url like "/sdcard/test.avi" and the other one is"/sdcard/test.mkv". I want to write an if statement that looks whether the last four characters of string is ".avi" or not in C. How can I do this? Using strcmp or what and how?
To get the last character of a string, use bracket notation to access the string at the last index, e.g. str[str. length - 1] . Indexes are zero-based, so the index of the last character in the string is str. length - 1 .
In other words, strings are compared letter-by-letter. The algorithm to compare two strings is simple: Compare the first character of both strings. If the first character from the first string is greater (or less) than the other string's, then the first string is greater (or less) than the second.
Simple approach should be taking Substring of an input string. var result = input. Substring(input. Length - 3);
strrchr() — Locate Last Occurrence of Character in String The strrchr() function finds the last occurrence of c (converted to a character) in string . The ending null character is considered part of the string . The strrchr() function returns a pointer to the last occurrence of c in string .
If you have a pointer-to-char array, str
, then this:
int len = strlen(str);
const char *last_four = &str[len-4];
will give you a pointer to the last four characters of the string. You can then use strcmp()
. Note that you'll need to cope with the case where (len < 4)
, in which case the above won't be valid.
How about this...
if (!strcmp(strrchr(str, '\0') - 4, ".avi")){
//The String ends with ".avi"
}
char *strrchr(const char *str, int c)
- Returns a pointer to the last matching char found in the string, including the NULL char if you so specify. In this case, I use it to get a pointer to the end of the string and then I move the pointer 4 steps back, thus giving a Pointer to the last 4 chars of the string.
I then compare the last 4 chars, to ".avi" and if they match, strcmp returns a 0 or logic FALSE, which I invert in my 'if' condition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With