Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Compare Last n Characters of A String to Another String in C

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?

like image 665
sjor Avatar asked Mar 14 '11 10:03

sjor


People also ask

How do you compare the last character of a string?

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 .

How do you compare characters in a string to a string?

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.

How do I get the last 3 characters of a string?

Simple approach should be taking Substring of an input string. var result = input. Substring(input. Length - 3);

How do you find the last occurrence of a character in a string?

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 .


2 Answers

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.

like image 168
Oliver Charlesworth Avatar answered Sep 21 '22 09:09

Oliver Charlesworth


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.

like image 37
John Byrne Avatar answered Sep 22 '22 09:09

John Byrne