在另一個字串變數中搜索一個字串變數,同時避免使用 <string.h> 庫中的任何函式。我不確定為什么我的代碼不起作用。非常感謝任何建議或替代方法。編輯:可以使用 strlen 但不能使用其他功能
#include <stdlib.h>
#include<string.h>
#include <stdio.h>
int strsearch(char *B, char *C);
int main()
{
char B[]= "thisatest";
char C[]= "tes";
strsearch(B, C);
return 0;
}
int strsearch(char *B, char *C ){
int i, b, c, k;
k= -1;
b= strlen(B);
c= strlen(C);
for (i=0; i<b; i ){
if (B[i c]== C)
return i;
return -1;
}
}
uj5u.com熱心網友回復:
你return -1;在回圈中。如果if (B[i c]== C)您進行的第一次比較失敗,它將回傳。將其移出回圈。
你比較錯誤的東西。B[i c]是一個char并且C是一個char*。如果要比較字串,使用strcmp,strncmp或memcmp視情況而定,并提供正確的引數。
strcmp對于要比較的任意字串,直到在兩者中都找到空終止符。strncmp如果您想將比較限制n為字符數但仍停留在空終止符處。似乎很適合子字串比較。memcmp如果您確定您提供的長度不會使其通過空終止符,因為它不檢查空終止符。它只是比較你告訴它的記憶體中的位元組,只要你告訴它。
我memcmp在這個例子中使用:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SS_NOTFOUND ((size_t)-1)
size_t strsearch(const char *B, const char *C) {
size_t Blen = strlen(B);
size_t Clen = strlen(C);
// If Blen < Clen, there's no way C can
// can be a substring of B:
if(Blen < Clen) return SS_NOTFOUND;
// Subtract the length of C from the length of B. There is no need to
// search in B beyond the point where C can't fit:
Blen -= Clen;
for (size_t i = 0; i <= Blen; i ) {
// memcmp is fine here since no null terminators will be passed
// due to the check (Blen < Clen) at the start and the subtraction
// of Clen from Blen above.
if (memcmp(B i, C, Clen) == 0) return i;
// char* char*
}
return SS_NOTFOUND;
}
int main() {
char B[] = "thisatest";
char C[] = "tes";
size_t pos = strsearch(B, C);
if(pos == SS_NOTFOUND) puts("sorry, not found");
else printf("Found at index %zu\n", pos);
}
輸出:
Found at index 5
如果您由于某種原因不能使用memcmp,請創建自己的并在上面的示例中使用它:
int MemCmp(const void *s1, const void *s2, size_t len) {
const unsigned char* a = s1;
const unsigned char* b = s2;
for(;len; --len, a, b) {
if(*a < *b) return -1;
else if(*a > *b) return 1;
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/407630.html
標籤:
上一篇:為什么我輸入字串的功能不起作用?
