如何最后n字符串的字符比较在C另一个字符串 [英] How to Compare Last n Characters of A String to Another String in C

查看:431
本文介绍了如何最后n字符串的字符比较在C另一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,我有两个字符串,其中之一就是像/sdcard/test.avi,另一种是/sdcard/test.mkv的URL。我想写一个if语句看起来字符串的最后四个字符是否是.AVI或不C.我怎样才能做到这一点?使用STRCMP或什么,以及如何?

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?

推荐答案

如果你有一个指针到字符数组, STR ,那么这样的:

If you have a pointer-to-char array, str, then this:

int len = strlen(str);
const char *last_four = &str[len-4];

会给你一个指向字符串的最后四个字符。然后,您可以使用的strcmp()。请注意,您需要处理,其中(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.

这篇关于如何最后n字符串的字符比较在C另一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆