指針我如何獲得一個字符的第一次出現在字符串中的指數爲int,而不是一個指向它的位置?獲取int,而不是從,和strchr
回答
如果你有兩個指針在C數組,你可以簡單地做:
index = later_pointer - base_address;
其中base_address
是數組本身。
例如:
#include <stdio.h>
int main (void) {
int xyzzy[] = {3,1,4,1,5,9}; // Dummy array for testing.
int *addrOf4 = &(xyzzy[2]); // Emulate strchr-type operation.
int index = addrOf4 - xyzzy; // Figure out and print index.
printf ("Index is %d\n", index); // Or use ptrdiff_t (see footnote a).
return 0;
}
,其輸出:
Index is 2
正如你可以看到,它縮放正確地給你指數不管底層類型(這不是問題爲char
但在一般情況下知道這一點很有用)。
因此,對於您的特定情況下,如果你的字符串是mystring
,並從strchr
返回值是chpos
,只是用chpos - mystring
獲得指數(假設你發現課程的特點,即chpos != NULL
)。
的(a)作爲正確地在註釋中指出的那樣,一個指針減法的類型是其中ptrdiff_t
,可以具有不同的範圍,以int
。
ptrdiff_t index = addrOf4 - xyzzy; // Figure out and print index.
printf ("Index is %td\n", index);
請注意,這隻會成爲一個問題,如果你的陣列足夠大的差異將不適合在int
:是完全正確的,該指數的計算和打印會更好的完成。這是可能的,因爲兩種類型的範圍沒有直接的關係的話,如果你非常重視可移植的代碼,你應該使用ptrdiff_t
變種。
使用指針運算:
char * pos = strchr(str, c);
int npos = (pos == NULL) ? -1 : (pos - str);
如果你處理的std :: string,而不是普通的C字符串,那麼你可以使用的std :: string :: find_first_of
http://www.cplusplus.com/reference/string/string/find_first_of/
這個問題是關於C,而不是C++。 –
他最初把它標記爲C++,我說「IF」:P –
- 1. 獲取符號而不是INT
- 2. 讀取位而不是int從插座
- 3. 獲得一個int,而不是浮動
- 4. 從Mysql獲取數據,而不是XML?
- 5. 從MySQL查詢獲取,而不是表
- 6. 從視頻獲取幀,而不是MediaMetadataRetriever
- 7. 從xmlhttp.responseText獲取HTML而不是JSON
- 8. 使用Python http請求獲取<response [200]>而不是INT
- 9. 從DataRow中獲取int值而不轉換爲字符串
- 10. Strchr和strncpy誤用
- 11. 獲得從int,而不是1:1的01在for循環中
- 12. 從abs(double)獲得雙倍結果而不是int
- 13. 獲取NaN而不是值
- 14. 獲取,而不是Microsoft.SharePoint.Client.FieldUserValue
- 15. ,和strchr從字符串值的指數
- 16. 應該int * p長int * p而不是?
- 17. int或char枚舉int,而不是ASCII
- 18. 和strchr使用和strtol將
- 19. Int而不是Long,bug?
- 20. string :: size_type而不是int
- 21. 從'int'獲取int型字符串
- 22. 從int獲取顏色
- 23. PHP從mysql獲取int值
- 24. 從oracle獲取int值to_date
- 25. 如何從Iterator獲取int []?
- 26. 從mysql_fetch_array獲取行號(int)
- 27. 從edittext獲取int的值
- 28. 如何從NSString獲取int?
- 29. 從int值獲取月份
- 30. 從JSON文件獲取int
應該提及一些關於sizeof(type)除以大於1字節的類型的數組的問題? –
@Mike,因爲C自動縮放指針算術,所以實際上並不需要它們是相同的類型。我已經添加了答案。 – paxdiablo
謝謝,這工作! – hesson