在字符数组查找字符串值 [英] Finding string values in a Char Array

查看:134
本文介绍了在字符数组查找字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个任务,我需要找到子阵列中的我。

I have an assignment where I need to find substrings in an array I have.

这是我的数组:

char DNA[] = {'A', 'G', 'C', 'G', 'G', 'G', 'A', 'C', 'C', 'G', 'T', 'C', 
      'C', 'C', 'G', 'A', 'C', 'A', 'T', 'T', 'G', 'A', 'T', 'G', 
      'A', 'A', 'G', 'G', 'G', 'T', 'C', 'A', 'T', 'A', 'G', 'A', 
      'C', 'C', 'C', 'A', 'A', 'T', 'A', 'C', 'G', 'C', 'C', 'A', 
      'C', 'C', 'A', 'C', 'C', 'C', 'C', 'A', 'A', 'G', 'T', 'T', 
      'T', 'T', 'C', 'C', 'T', 'G', 'T', 'G', 'T', 'C', 'T', 'T', 
      'C', 'C', 'A', 'T', 'T', 'G', 'A', 'G', 'T', 'A', 'G', 'A', 
      'T', 'T', 'G', 'A', 'C', 'A', 'C', 'T', 'C', 'C', 'C', 'A', 
      'G', 'A', 'T', 'G', '\0'};

用户将输入一个字符串,如CAT,我会需要做一个程序,使得printf语句将显示CAT的地方发现的元素。

The user will enter a string such as CAT and I'll need to make a program such that the printf statement will display the elements of where CAT is found.

我尝试使用功能的strstr但这只是给我的数组中的第一次出现。但是,如果CAT多次出现,也不会打印出报表,所以即时知道我应该怎么做呢?

I tried using the strstr function but this only gives me the first occurence in the array. However, if CAT appears more than once, it will not print that statement out, so im wondering how should I do this?

这是我迄今为止:

char input [100];

char DNA[] = {'A', 'G', 'C', 'G', 'G', 'G', 'A', 'C', 'C', 'G', 'T', 'C', 
      'C', 'C', 'G', 'A', 'C', 'A', 'T', 'T', 'G', 'A', 'T', 'G', 
      'A', 'A', 'G', 'G', 'G', 'T', 'C', 'A', 'T', 'A', 'G', 'A', 
      'C', 'C', 'C', 'A', 'A', 'T', 'A', 'C', 'G', 'C', 'C', 'A', 
      'C', 'C', 'A', 'C', 'C', 'C', 'C', 'A', 'A', 'G', 'T', 'T', 
      'T', 'T', 'C', 'C', 'T', 'G', 'T', 'G', 'T', 'C', 'T', 'T', 
      'C', 'C', 'A', 'T', 'T', 'G', 'A', 'G', 'T', 'A', 'G', 'A', 
      'T', 'T', 'G', 'A', 'C', 'A', 'C', 'T', 'C', 'C', 'C', 'A', 
      'G', 'A', 'T', 'G', '\0'};

printf("enter string ");
scanf("%s", &input);

char *find;

find = strstr(DNA, input);

if (find != NULL)
{
    printf("the string is found at element %d\n", (find - DNA)+1);
}

如果我输入cat,程序会说,它在元件17,但有一只猫在单元74。

If I type CAT, the program will say its at element 17, but there is another CAT at element 74.

推荐答案

一种方法是你的if语句改为while循环,修改找到在每次迭代。需要注意的是,就像 DNA 找到还引用一个字符指针 - 只是在字符串中的不同位置。因此,该字​​符串的其余部分可以简单地通过使用 ++找到作为起点访问。

One approach would be to change your if statement to a while loop, modifying find on each iteration. Note that, just like DNA, find also references a character pointer - just at a different location in the string. Therefore, the rest of the string can be accessed simply by using ++find as your starting point.

while(find != NULL){
    printf("the string is found at element %d\n", (find - DNA)+1);
    find = strstr(++find, input);
}

这会产生一个相当原油产量,但它给你一些帮助。

This produces a fairly crude output, but it gives you something to work with.

这篇关于在字符数组查找字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆