2010-07-10 107 views
23

假設我有一個字符串"qwerty",我希望找到其中e字符的索引位置。 (在這種情況下,索引應該是2如何找到C中字符串中的字符索引?

如何在C中執行此操作?

我找到了strchr函數,但它返回一個指向字符而不是索引的指針。

+0

可能重複C](http://stackoverflow.com/questions/4824/string-indexof-function-in-c) – 2015-07-29 13:52:32

回答

47

距離和strchr什麼回報減去字符串地址:

char *string = "qwerty"; 
char *e; 
int index; 

e = strchr(string, 'e'); 
index = (int)(e - string); 
+0

down-voter:代碼有什麼問題嗎? – wj32 2010-07-10 03:00:25

+0

這是「正確的」,但理論上可怕的是,標準中沒有任何東西可以阻止一個字符串的長度超過一個普通的'int'的容量。如果您可以依賴於C99,請使用uintptr_t(在stdint.h中定義)。它也應該消除對該演員的需求。 – 2010-07-10 03:43:42

+4

指針差異的結果是ptrdiff_t。 – Nyan 2010-07-10 04:19:16

3
void myFunc(char* str, char c) 
{ 
    char* ptr; 
    int index; 

    ptr = strchr(str, c); 
    if (ptr == NULL) 
    { 
     printf("Character not found\n"); 
     return; 
    } 

    index = ptr - str; 

    printf("The index is %d\n", index); 
    ASSERT(str[index] == c); // Verify that the character at index is the one we want. 
} 

此代碼是未經測試的當前,但它體現了正確的概念。

4

您也可以使用strcspn(string, "e"),但這可能會慢得多,因爲它能夠處理多個可能字符的搜索。使用strchr並減去指針是最好的方法。

0

什麼:

char *string = "qwerty"; 
char *e = string; 
int idx = 0; 
while (*e++ != 'e') idx++; 

複製到e保留原始的字符串,我想如果你不在乎,你可以只工作在*串

[String.indexOf功能的