我正在使用一个用 C 编写的程序,该程序涉及比较连字符的姓氏。例如,它可能会将 Mary Jay-Blige 与 Mary Kay-Blige 进行比较。
查找连字符并将变量设置为其位置的代码是:
APT_String LAST_NAME
char * p_ich;
int iPosHyphen;
p_ich = strchr(LAST_NAME,'-');
iPosHyphen = p_ich-LAST_NAME+1;
其中 APT_String 是 IBM DataStage 的数据类型。
我继承了上面的代码,它似乎“有效”,但我想对 p_ich-LAST_NAME+1
操作进行一些澄清。
也就是说,如果 strchr()
返回第一个“-”的位置,C 如何处理这个算术?
如果我调用 cout<,我会得到 -Blige
。所以我猜一旦找到指定的字符它就会返回字符串的其余部分?
I'm working with a program written in C that involves comparing hypehenated surnames. For example, it might compare Mary Jay-Blige to Mary Kay-Blige.
The code that finds the hyphen and sets a variable to it's position is:
APT_String LAST_NAME
char * p_ich;
int iPosHyphen;
p_ich = strchr(LAST_NAME,'-');
iPosHyphen = p_ich-LAST_NAME+1;
where APT_String is a data type for IBM's DataStage.
I inherited the above code, and it appears to "work", but I would like some clarification on the p_ich-LAST_NAME+1
operation.
Namely, if strchr()
returns the location of the first '-', how is C handling this arithmetic?
If I call cout<<p_ich;
, I get -Blige
. So I guess it returns the remainder of the string once the specified char is found?
发布评论
评论(2)
是的,strchr 返回第一次出现的地址(不是索引)。因此,从中减去原始字符串(地址)即可得到连字符的位置。但在这里 +1 可以让你找到连字符之后的第一个位置(索引)。
这样 p_ich[iPosHyphen] == 'B'。
Yes, strchr returns the address of the first occurence (not the index). So you subtract the original string (address) from that to get the position of the hyphen. But here the +1 gets you the first position (index) after the hyphen.
Such that p_ich[iPosHyphen] == 'B'.
这是非常基本的 C 指针算术,您可以轻松找到很多有关它的信息。
将一个指针减去另一个指针会产生它们索引之间的距离,就好像它们是同一数组的一部分一样。在您的示例中,它将是 *p_ich* 和 *LAST_NAME* 之间的距离。
对于标准 char 类型距离将等于内存地址之间的差,但一般来说:
This is very basic C pointer arithmetic and you can easily find a lot of information about it.
Subtracting one pointer from another yields distance between their indices as if they were part of the same array. In your example it will be distance between *p_ich* and *LAST_NAME*.
With standard char type distance will be equal to difference between memory addresses but in general: