[英]How to find base address of same char in string array using pointers in C language?
我輸入了一個字符串,然后嘗試在字符串中找到一個char
的地址,但是問題是我無法使用指針在字符串中找到相同char
的地址。
例如,當輸入為"ALLEN"
我需要兩個'L'
的地址,但是我的程序僅輸出第一個'L'
的地址。
我嘗試了if ... else
和for
-loop,但是我無法解決問題。
#include <stdio.h>
#include <string.h>
main()
{
char a, str[81], *ptr;
printf("\nEnter a sentence:");
gets(str);
printf("\nEnter character to search for:");
a = getchar();
ptr = strchr(str,a);
/* return pointer to char*/
printf( "\nString starts at address: %d",str);
printf("\nFirst occurrence of the character (%c) is at address: %d ", a,ptr);
}
如果我正確理解您的意見:
要查找同一角色的其他出現,只需在最后一次已知出現之后尋找它們即可。 因此,您將編寫如下內容:
{
const char* next_occurrence = strchr(str, a);
while (next_occurrence != NULL) {
printf(
"Character %c occurs in string \"%s\" at position %p\n",
a, str, next_occurrence - str);
next_occurrence = strchr(next_occurrence + 1, a);
}
}
您會注意到, next_occurrence + 1
是我們剛剛發現的第一個字符的地址。
只需再次調用strchr
:
ptr = strchr(str,a);
if (ptr != NULL)
ptr2 = strchr (ptr + 1, a);
注意strchr
的第一個參數是ptr + 1
,因此我們從已經找到的字符之后開始搜索字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.