【问题标题】:searching substrings in char array [duplicate]在char数组中搜索子字符串[重复]
【发布时间】:2014-01-06 02:44:57
【问题描述】:

据我所知,C++ 字符串中有一个执行子字符串搜索的函数:string1.find(string2)。

有没有办法在 char 中执行相同的操作?以下是我的问题:

    #include <iostream>
    #include <cstring>
    using namespace std;
    int main()
    { 
      char a[]="hello world!";
      char b[]="el";
      //find substring b[] in a[]


    }

假设我需要在字符串中找到子字符串“el”,可以这样做吗?

【问题讨论】:

  • strstr,但与仅使用 std::string 相比,它更像 C。
  • @godel9,这个问题是在询问一种在 char 数组中查找子字符串的方法。您那里的链接只是要求一种从 char 数组中复制某个字符串的方法,这仅在找到要复制的字符串后才对这个问题有用
  • @godel9 该操作要求使用 C++ 方法从某个字符串中查找和提取子字符串。被标记为重复的帖子不回答该问题。它回答了如何从 C(不是 C++)中的 const char 中复制和找到子字符串的问题。我确信这个问题是一些关于堆栈溢出的问题的重复,但它不是上述问题的重复。

标签: c++


【解决方案1】:
char *output = NULL;
output = strstr (a,b);
if(output) {
    printf("String Found");
}

【讨论】:

  • 谢谢。有用!我在做与 Linux 系统相关的最后一年项目时需要这个。真的非常感谢!
  • strstr 在某些实现中返回const char*
【解决方案2】:

这应该可行:

char a[]="hello world!";
char b[]="el";
//find substring b[] in a[]
string str(a);
string substr(b);

found = str.find(substr);

【讨论】:

    猜你喜欢
    • 2014-03-26
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 2016-11-15
    • 2011-07-04
    • 1970-01-01
    相关资源
    最近更新 更多