-3
我需要比較最後一個空格字符後面的單詞的2個字符串。 例如:比較字符串後的最後一個單詞在空格後c
str1 = "tran tuan hien"
str2 = "doan tuan"
我需要返回的函數-1當我調用函數(STR1,STR2); (就像strcmp(「hien」,「tuan」)返回-1)。 c或C++有這樣的功能嗎?
我需要比較最後一個空格字符後面的單詞的2個字符串。 例如:比較字符串後的最後一個單詞在空格後c
str1 = "tran tuan hien"
str2 = "doan tuan"
我需要返回的函數-1當我調用函數(STR1,STR2); (就像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
@thanh我很抱歉。第一個函數的實現是錯誤的。看到我更新的帖子。 – 2015-03-13 16:21:12
是什麼類型str1和STR2的? – 2015-03-13 15:03:53
在空白處分割字符串(http://stackoverflow.com/questions/236129/split-a-string-in-c?page=1&tab=votes#tab-top),或使用strtok(http:// www.cplusplus.com/reference/cstring/strtok/),然後比較最終的標記。 – user2970916 2015-03-13 15:07:21
我問過點什麼嗎?我只是刪除了不需要的'C++'標記。 – shauryachats 2015-03-13 15:08:35