在C中查找字符串中子字符串位置 [英] In C find position of substring in a string

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

问题描述

这里是一个接受:

的程序
  1. 来自用户的句子。
  2. 来自用户的单词。

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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    char sntnc[50], word[50], *ptr[50];
    int pos;
    puts("
Enter a sentence");
    gets(sntnc);
    fflush(stdin);
    puts("
Enter 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;

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

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