按c中空格后的最后一个单词比较字符串

标签 c string

我需要通过最后一个空格字符之后的单词来比较两个字符串。 示例:

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/

相关文章:

c# - 为什么我们应该将 ToString 方法与 StringBuilder 一起使用?

Char 等于 C 中的 char 变量

string - 带符号数字的字符串算术表达式分段算法

C:scanf 和 getchar 行为的差异

c - syscalls.h 中的 sys_ 函数未定义

c - C 中的大数组初始化问题

java - java中StringBuilder.append()的时间复杂度是多少?

C++内存流到C文件流

c - 主 pty 如何检测从 tty 是否已退出?

c - 在 C 中将字符串添加到文本文件