如何解析char数组的结尾?

时间:2013-04-27 18:51:03

标签: c arrays parsing char c-strings

所以,假设我有一行看起来像这样:

"abcdefghi"

如果我想要“hi”,并且之后没有任何内容,我该如何解析?

我试过strtok(str, "'\0'"),但似乎无法让它发挥作用。

C中是否有允许我这样做的功能?

2 个答案:

答案 0 :(得分:2)

首先,程序早期需要声明和定义:

#include <string.h>
…
char y[3]; // Define array to hold results.

然后可以复制x的最后两个字符和终止空字符:

// Find length of string.
size_t length = strlen(x);

// Copy last two characters.
strcpy(y, x+length-2);

请注意,这要求x至少包含两个字符。

或者,可以使用以下命令复制没有终止空字符的两个字符:

// Find length of string.
size_t length = strlen(x);

// Copy last two characters without the terminating null character.
strncpy(y, x+length-2, 2);

或者:

// Find length of string.
size_t length = strlen(x);

// Copy last two characters without the terminating null character.
y[0] = x[length-2];
y[1] = x[length-1];

答案 1 :(得分:0)

您可以使用strstr在字符串中查找子字符串。

char * pointsToHi = strstr( string , "hi") ;