返回一个指针,该指针指向出现在给定C字符串中的单词的首次出现

问题描述

我一直很难弄清楚如何将指针指向给定C字符串中单词的第一个字符。问题出在这里:编写函数findFirst()。该函数具有两个参数:指向C样式字符串中第一个字符的const char * s1和const char * s2。返回指向s2出现在s1内部的指针,如果s2没有出现在s内部,则返回nullptr(0)。

这是我的代码

#include <cstddef>  // size_t for sizes and indexes
#include <iostream>
using namespace std;

const char* findFirst(const char *s1,const char *s2)
{
    while (*s1)     // go through each element in s1
    {
      ++s1;
        if (*s1 == *s2)
        {
          while(*s2)
          {
            ++s1;
            ++s2;
            if (*s1 == *s2 && *s2 == '\0' - 1)
                return s1;
          }
        }
    }
    return nullptr;
}

int main() 
{
  const char * b = findFirst("Find me in this line","me"); 
  cout << b << endl;
}

解决方法

这基本上是重新做strstr函数。

您可以找到解决方案here

引自链接的问题:

功能描述为:

strstr()函数在s1指向的字符串中找到s2指向的字符串中字符序列(不包括终止空字符)的第一个匹配项。

strstr函数返回指向所定位字符串的指针,如果未找到该字符串,则返回空指针。如果s2指向长度为零的字符串,则函数返回s1。


char *findFirst(const char *s1,const char *s2)
{
    const char *a;
    const char *b;

    b = s2;

    if (*b == 0) {
        return (char *) s1;
    }

    for ( ; *s1 != 0; s1 += 1) {
        if (*s1 != *b) {
            continue;
        }

        a = s1;
        while (1) {
            if (*b == 0) {
                return (char *) s1;
            }
            if (*a++ != *b++) {
                break;
            }
        }
        b = s2;
    }

    return NULL;
}
,

对于初学者,您可以使用执行任务的标准C函数strstr

如果您需要自己编写类似的函数,则可以用不同的方法来实现。例如

#include <iostream>
#include <cstring>

const char * findFirst( const char *s1,const char *s2 )
{
    bool found = false;
    
    size_t n1 = std::strlen( s1 );
    size_t n2 = std::strlen( s2 );
    
    if ( !( n1 < n2 ) )
    {
        for ( const char *last = s1 + n1 - n2 + 1; !found && s1 != last;  )
        {
            size_t j = 0;
            
            while ( s2[j] && s2[j] == s1[j] ) ++j;
            
            if ( !( found = s2[j] == '\0' ) ) ++s1;
        }
    }

    return found ? s1 : nullptr; 
}

int main() 
{
    std::cout << findFirst( "Find me in this line","me" ) << '\n';
    
    return 0;
}

程序输出为

me in this line

代替for循环中的这些语句

size_t j = 0;

while ( s2[j] && s2[j] == s1[j] ) ++j;

if ( !( found = s2[j] == '\0' ) ) ++s1;

您可以使用唯一的语句

if ( !( found = memcmp( s1,s2,n2 ) == 0 ) ) ++s1;

如果不允许使用标准的C字符串函数,则可以通过以下方式实现函数strlen(例如,应重命名为string_length

size_t string_length( const char *s )
{
    size_t n = 0;

    while ( s[n] ) ++n;

    return n;
}

关于函数的实现,甚至是第二条语句

while (*s1)     // go through each element in s1
{
  ++s1;
  //...

例如,如果第二个字符串与第一个字符串的开头重合,则会使函数出错,因为您增加了指针s1