简体   繁体   English

如何使用C语言中的指针在字符串数组中查找相同字符的基址?

[英]How to find base address of same char in string array using pointers in C language?

I input a string and then try to find an address of a char within the string but the problem is that I am unable to find the address of the same char in the string using pointers. 我输入了一个字符串,然后尝试在字符串中找到一个char的地址,但是问题是我无法使用指针在字符串中找到相同char的地址。

For example when input is "ALLEN" I need the addresses of both 'L' s but my program only prints the address of the first 'L' . 例如,当输入为"ALLEN"我需要两个'L'的地址,但是我的程序仅输出第一个'L'的地址。

I tried if ... else and a for -loop but I can't solve the problem. 我尝试了if ... elsefor -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);  
}

If I understood you correctly: 如果我正确理解您的意见:

To find additional occurrences of the same character, just look for them after the last known occurrence. 要查找同一角色的其他出现,只需在最后一次已知出现之后寻找它们即可。 So, you would write something like this: 因此,您将编写如下内容:

{
    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);
    }
}

You'll note that next_occurrence + 1 is the address of the first character after the occurrence we've just found. 您会注意到, next_occurrence + 1是我们刚刚发现的第一个字符的地址。

Just call strchr again: 只需再次调用strchr

ptr = strchr(str,a);
if (ptr != NULL)
    ptr2 = strchr (ptr + 1, a);

Notice the first parameter to strchr is ptr + 1 , so we start searching with the character after the one we already found. 注意strchr的第一个参数是ptr + 1 ,因此我们从已经找到的字符之后开始搜索字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM