繁体   English   中英

在C中找到子串在字符串中的位置

[英]In C find position of substring in a string

这是一个接受以下程序:

  1. 用户的句子。
  2. 用户的话。

我如何找到句子中输入单词的位置?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    char sntnc[50], word[50], *ptr[50];
    int pos;
    puts("\nEnter a sentence");
    gets(sntnc);
    fflush(stdin);
    puts("\nEnter a word");
    gets(word);
    fflush(stdin);
    ptr=strstr(sntnc,word);

    //how do I find out at what position the word occurs in the sentence?

    //Following is the required output
    printf("The word starts at position #%d", pos);
    return 0;
}

ptr指针将指向word的开头,因此您可以从中减去句子指针sntnc的位置:

pos = ptr - sntnc;

strstr()的返回是指向“单词”首次出现的指针,因此

pos=ptr-sntc;

这仅适用,因为sntc和ptr是指向相同字符串的指针。 为了澄清我说的是何时发生,当在目标字符串中找到匹配字符串时,它是第一个匹配字符的位置。

仅供参考:

char saux[] = "this is a string, try to search_this here";
int dlenstr = strlen(saux);
if (dlenstr > 0)
{
    char *pfound = strstr(saux, "search_this"); //pointer to the first character found 's' in the string saux
    if (pfound != NULL)
    {
        int dposfound = int (pfound - saux); //saux is already pointing to the first string character 't'.
    }
}

您可以使用此简单的strpos修改

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int strpos(char *haystack, char *needle, int offset);
int main()
{
    char *p = "Hello there all y'al, hope that you are all well";
    int pos = strpos(p, "all", 0);
    printf("First all at : %d\n", pos);
    pos = strpos(p, "all", 10);
    printf("Second all at : %d\n", pos);
}


int strpos(char *hay, char *needle, int offset)
{
   char haystack[strlen(hay)];
   strncpy(haystack, hay+offset, strlen(hay)-offset);
   char *p = strstr(haystack, needle);
   if (p)
      return p - haystack+offset;
   return -1;
}

由于某些原因,我在使用strstr()时遇到了麻烦,并且我还想要索引。

我使用此函数来查找较大字符串(如果存在)中子字符串的位置,否则返回-1。

 int isSubstring(char * haystack, char * needle) {
     int i = 0;
     int d = 0;
     if (strlen(haystack) >= strlen(needle)) {
         for (i = strlen(haystack) - strlen(needle); i >= 0; i--) {
             int found = 1; //assume we found (wanted to use boolean)
             for (d = 0; d < strlen(needle); d++) {
                 if (haystack[i + d] != needle[d]) {
                     found = 0; 
                     break;
                 }
             }
             if (found == 1) {
                 return i;
             }
         }
         return -1;
     } else {
         //fprintf(stdout, "haystack smaller\n"); 
     }
 } 

我对此线程的原始帖子的评论:此声明不正确:

    char sntnc[50], word[50], *ptr[50];

C代码甚至不会编译:它将在此行上失败:

    ptr = strstr(sntnc,word);

因此,该行应更改为:

   char sntnc[50], word[50], *ptr;

而且您不需要分配给“ ptr字符串”的内存。 您只需要一个指向char的指针。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM