C 中的子串
鉴于我已经声明:
char **string;
如何将其传递到另一个函数,其中子字符串从某个位置开始?
我目前将其设置为:
function((*string)[pos])
打算将其作为从位置 pos
开始的子字符串。有什么建议吗?
Given I have declared:
char **string;
How do I pass it into another function with a substring starting at a certain position?
I currently have it as:
function((*string)[pos])
intending it to be a substring that begins at position pos
. Any advice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
string
的类型是char **
。string
的类型为char **
。 (指向您的字符串的指针)*string
的类型为char *
。 (字符串本身)**string
的类型为char
。 (字符串中的一个字母)因此您想要偏移到字符串本身:
其类型为
char *
。The type of
string
ischar **
.string
is of typechar **
. (pointer to your string)*string
is of typechar *
. (the string itself)**string
is of typechar
. (a letter in the string)So you want to offset into the string itself:
which will have type
char *
.或者
or
(*string)[pos]
表示位置pos
处的字符。您可能需要(*string) + pos
来代替。(*string)[pos]
denotes the char at positionpos
. You probably want(*string) + pos
instead.您可以将整个字符串的指针以及整数长度传递给函数,函数将在其逻辑中考虑该长度。
或者,您可以使用指针算术提取特定的子字符串(假设您只想删除字符串前面的字符):
现在, y 指向字符串“text”。 http://codepad.org/icVjE6in
或者,提取具有特定开始和结束位置的子字符串需要使用该和strncpy。
You could pass the pointer of the whole string to the function along with an integer length, which the function will take into consideration in its logic.
Or, you can extract a specific substring (assuming you want to only trim characters off the front of the string) by using pointer arithmetic:
Now, y is pointing to the string "text". http://codepad.org/icVjE6in
Or, extracting a substring with a specific start and end would require using that and strncpy.
我知道有两种方法可以做到这一点。它们都需要一个
char*
,因此您正在使用的字符串在您的情况下是*string
(string
是指向*string
的指针) code>char* 表示字符串,因此您必须取消引用它才能获取实际的字符串)。第一个是简单的指针加法,如
(*string) + 7
所示。这将为您提供从第八个字符开始的字符串。第二个是获取起始字符的地址,如
&((*string)[7])
。仅当字符串长度至少为第八个字符时,这两种方法才会“起作用”。换句话说,不要试图超越字符串的末尾。
There are two ways I know of to do this. Both of them require a
char*
so the string you're working with is*string
in your case (string
is the pointer to thechar*
representing the string, so you have to dereference it to get the actual string).The first is simple pointer addition, as in
(*string) + 7
. This gives you the string starting at the eighth character.The second is to get the address of the starting character, as in
&((*string)[7])
.Both of these will only "work" if you're string is at least eighth characters long. In other words, don't try to look beyond the end of the string.