如何让子在C与和strchr [英] how to get substring in c with strchr
问题描述
我想取一个字符串的一部分。结果
我有以下的code:
I'm trying to fetch part of a string.
I have the following code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char mystring[]="The quick brown fox jumps over the lazy dog";
char word1[]="The";
char * posb,pose;
char * word2;
int b,e,n;
n=memcmp(mystring, word1, sizeof(word1)-1);
if (n==0) printf("the first word is found!\n");
posb=strchr(mystring,' '); // posb will be a pointer to the first character
b=posb-mystring+1;
printf("posb -> %d\n",posb);
printf("b -> %d\n",b);
pose=strchr(mystring+b+1,' '); // pose will be a pointer to the second character
printf("calc e\n");
e=pose-sizeof(mystring)+1;
printf("pose -> %s\n",pose);
printf("e -> %d\n",e);
word2 = (char*) malloc (sizeof(char)*(e-b));
memcpy(word2, posb, sizeof(word2));
printf("%s:%i:%i:%i\n",word2, b, e, e-b);
free (word2);
的问题越来越第二个字并将其存储在WORD2。为此,我尝试使用和strchr
来定位的空间。但是我用的是第二次和strchr
我需要一个偏移找到第二空间。我试过如下:
The problem is getting the second word and store it in word2. For this I try using strchr
to locate the spaces. But the second time I use strchr
I need an offset to find the second space. I tried the following:
pose=strchr(mystring+b+1,' ');
pose=strchr(&mystring[b+1],' ');
变量 B
和电子
应包含 mystring中空格字符的位置
。 字词2
应包含快速
最后。结果
另一种解决方案是使用一个循环的字符串'穿行',但是这将是欺骗和strchr
功能。
The variables b
and e
should contain the positions of the space character in mystring
. word2
should contain quick
eventually.
Another solution would be to 'walk through' the string using a loop, but that would be cheating the strchr
function.
推荐答案
为了获得第二个字,请在此
In order to get the second word, check this
char mystring[] = "The quick brown fox jumps over the lazy dog";
char word1[] = "The";
char * posb, pose;
char * word2;
int b, e, n;
n = memcmp(mystring, word1, sizeof(word1)-1);
if (n == 0) printf("the first word is found!\n");
posb = strchr(mystring, ' '); // posb will be a pointer to the first character
b = posb - mystring + 1;
printf("posb -> %d\n", posb);
printf("b -> %d\n", b);
posb = strchr(posb + 1, ' '); // pose will be a pointer to the second character
printf("calc e\n");
e = posb - mystring + 1;
printf("e -> %d\n", e);
word2 = (char*)malloc(sizeof(char)*(e - b));
memcpy(word2, mystring + b, e - b);
word2[e-b-1] = '\0';
printf("%s:%i:%i:%i\n", word2, b, e, e - b);
free(word2);
这篇关于如何让子在C与和strchr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!