我需要通过最后一个空格字符之后的单词来比较两个字符串。 示例:
str1 = "tran tuan hien"
str2 = "doan tuan"
我需要一个在调用 function(str1, str2); 时返回 -1 的函数; (就像 strcmp("hien", "tuan") 返回 -1 一样)。 c或c++有类似的函数吗?
最佳答案
这是一个演示程序,展示了如何用 C 语言编写该函数
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int cmp_last_word( const char s1[], const char s2[] )
{
const char *p1 = s1 + strlen( s1 );
while ( p1 != s1 && isblank( *( p1 - 1 ) ) ) --p1;
const char *q1 = p1;
while ( q1 != s1 && !isblank( *( q1 -1 ) ) ) --q1;
const char *p2 = s2 + strlen( s2 );
while ( p2 != s2 && isblank( *( p2 - 1 ) ) ) --p2;
const char *q2 = p2;
while ( q2 != s2 && !isblank( *( q2 -1 ) ) ) --q2;
while ( q1 != p1 && q2 != p2 && *q1 == *q2 ) ++q1, ++q2;
if ( q1 == p1 && q2 == p2 ) return 0;
else if ( q1 == p1 && q2 != p2 ) return -1;
else if ( q1 != p1 && q2 == p2 ) return 1;
else return ( *q1 < *q2 ) ? -1 : 1;
}
int main(void)
{
char str1[] = "tran tuan hien ";
char str2[] = "doan tuan \t";
printf( "%d\n", cmp_last_word( str1, str2 ) );
strcpy( str2, "doan hien \t" );
printf( "%d\n", cmp_last_word( str1, str2 ) );
return 0;
}
程序输出为
-1
0
关于按c中空格后的最后一个单词比较字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29035514/