web-dev-qa-db-fra.com

En C trouver la position de la sous-chaîne dans une chaîne

Voici un programme pour accepter un: 

  1. Phrase d'un utilisateur.
  2. Mot d'un utilisateur.

Comment trouver la position de la parole entrée dans la phrase?

#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;
}
7
Mugambo

Le pointeur ptr pointe vers le début de Word. Vous pouvez donc simplement soustraire l'emplacement du pointeur de phrase, sntnc:

pos = ptr - sntnc;
17
Gingi

Juste pour référence:

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'.
    }
}
4
xtrm

Le retour de strstr () est un pointeur sur la première occurrence de votre "mot", donc 

pos=ptr-sntc;

Cela ne fonctionne que parce que sntc et ptr sont des pointeurs sur la même chaîne. Pour clarifier lorsque je parle d’occurrence, il s’agit de la position du premier caractère correspondant lorsque la chaîne correspondante est trouvée dans la chaîne cible.

4
Ralph Johnson

Vous pouvez utiliser cette simple modification de 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;
}
3
Howard J

Pour certaines raisons, j'avais des problèmes avec strstr (), et je voulais aussi indexer. 

J'ai créé cette fonction pour trouver la position de la sous-chaîne dans une chaîne plus grande (si existante), sinon je retourne -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"); 
     }
 } 
2
Pranav Nandan

Mon commentaire à la publication ORIGINAL dans ce fil de discussion: Cette déclaration est INCORRECT:

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

Le code C ne serait même pas compilé: il échouerait sur cette ligne:

    ptr = strstr(sntnc,Word);

Donc, la ligne doit être changée en: 

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

Et vous n'avez PAS besoin de mémoire allouée à 'ptr string'. Vous avez juste besoin d'un pointeur sur char.

0
derlo