我只是想从字符串中提取特定的单词 我的节目是:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 100
int main() {
FILE *f;
char buffer[100];
char buf[100];
int count=0;
char res[100];
f=fopen("1JAC.pdb","rb");
while(fgets(buffer,BUFFER_SIZE,f))
{
if(strncmp(buffer,"ATOM",4)==0 && strncmp(buffer+13,"CA",2)==0 && strncmp(buffer+21,"A",1)==0)
{
strcpy(buf,buffer);
}
printf (buf);
该计划的输出是
ATOM 1033 CA LEU A 133 33.480 94.428 72.166 1.00 16.93 C
我只想提取单词&#34; LEU&#34;使用子字符串。我试过这样的事情:
Substring(17,3,buf);
但它不起作用...... 有人可以告诉我C中的子字符串。
答案 0 :(得分:1)
Memcpy似乎是最好的方法......
memcpy( destBuff, sourceBuff + 17, 3 );
destBuff[ 3 ] = '\0';
请记住在需要时添加空终止符(正如我在示例中所做的那样)。
之前已经回答过这个问题,在Stack-overflow上已经多次了
答案 1 :(得分:1)
//Use the following substring function,it will help you.
int main(int argc, char *argv[])
{
FILE *filepointer;
char string[1700];
filepointer=fopen("agg.txt", "r");
if (filepointer==NULL)
{
printf("Could not open data.txt!\n");
return 1;
}
while (fgets(string, sizeof(string), filepointer) != NULL)
{
char* temp=substring(string,17,3);/*here 17 is the start position and 3 is the length of the string to be extracted*/
}
return 0;
}
char *substring(char *string, int position, int length)
{
char *pointer;
int c;
pointer = (char*) malloc(length+1);
if (pointer == NULL)
{
printf("Unable to allocate memory.\n");
exit(1);
}
for (c = 0 ; c < length ; c++)
{
*(pointer+c) = *(string+position-1);
string++;
}
*(pointer+c) = '\0';
return pointer;
}
答案 2 :(得分:0)
char out[4] = {0};
strncpy(out, buf+17, 3);