简体   繁体   English

从strchr获取int而不是指针

[英]Get int instead of pointer from strchr

如何获取字符串中字符首次出现的索引作为int而不是指向其位置的指针?

If you have two pointers to an array in C, you can simply do: 如果您在C中有两个指向数组的指针,则只需执行以下操作:

index = later_pointer - base_address;

where base_address is the array itself. 其中base_address是数组本身。

For example: 例如:

#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;
}

which outputs: 输出:

Index is 2

As you can see, it scales correctly to give you the index regardless of the underlying type (not that it matters for char but it's useful to know in the general case). 如您所见,无论底层类型如何,它都可以正确缩放以提供索引(这对于char并不重要,但在一般情况下很有用)。

So, for your specific case, if your string is mystring and the return value from strchr is chpos , just use chpos - mystring to get the index (assuming you found the character of course, ie, chpos != NULL ). 因此,对于您的特定情况,如果您的字符串是mystring ,而strchr的返回值是chpos ,则只需使用chpos - mystring来获取索引(假设您当然找到了字符,即chpos != NULL )。


(a) As rightly pointed out in a comment, the type of a pointer subtraction is ptrdiff_t which, may have a different range to int . (a)正如在注释中正确指出的,指针减法的类型是ptrdiff_t ,它与int范围可能不同。 To be perfectly correct, the calculation and printing of the index would be better done as: 完全正确地讲,索引的计算和打印将更好地做到以下几点:

    ptrdiff_t index = addrOf4 - xyzzy;       // Figure out and print index.
    printf ("Index is %td\n", index);

Note that this will only become an issue if your arrays are large enough that the difference won't fit in an int . 请注意,仅当您的数组足够大以至于差值不能适合int ,这才成为问题。 That's possible since the ranges of the two types are not directly related so, if you value portable code highly, you should use the ptrdiff_t variant. 这是可能的,因为这两种类型的范围并不直接相关,因此,如果您高度重视可移植代码,则应使用ptrdiff_t变体。

Use pointer arithmetic: 使用指针算法:

char * pos = strchr( str, c );
int npos = (pos == NULL) ? -1 : (pos - str);

if you're dealing with std::string and not plain c-strings then you can use std::string::find_first_of 如果您正在处理std :: string而不是纯c字符串,则可以使用std :: string :: find_first_of

http://www.cplusplus.com/reference/string/string/find_first_of/ http://www.cplusplus.com/reference/string/string/find_first_of/

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

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