【问题标题】:I need assistance with Strings in C [closed]我需要 C 中的字符串方面的帮助 [关闭]
【发布时间】:2013-09-26 04:34:54
【问题描述】:

我是 C 语言的新手,我遇到了这个问题。谁能帮我解答一下。

尝试编写一个函数,它有两个字符串类型的参数。返回值告诉你第一个字符串是否是第二个参数字符串的子字符串

【问题讨论】:

  • 必填项:您尝试过什么?兄弟/姐妹,我们只能帮助你自己。
  • 启动你:: Google strstr 及其逻辑。
  • 提问前请先努力。
  • Google/Bing 是您学习字符串的助手。

标签: c string function


【解决方案1】:
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

bool contains_substring(const char *str1, const char *str2) {
    if (strstr(str1, str2) != NULL) {
        return true;
    }
    else {
        return false;
    }
}

int main() {
    const char *str1 = "This is a test";//this is the string that you will be comparing against
    const char *str2 = "test";//this is the substring you're searching for.
    if (!contains_substring(str1, str2)) {
        printf("No match found!\n");
    }
    else {
        printf("String 1 contains String 2\n");
    }
    return 0;
}

注意:因为这个例子使用 stdbool 作为 bool 类型,所以这个例子必须使用 C99 选项 -std=c99 和 gcc 或类似 clang 的相关编译器进行编译,如下所示:

gcc inputfile.c -std=c99 -o outputbinaryfilename

当然,您可以通过将 bool 定义为以下内容(来自 here)来规避包含该库并完全使用额外的编译器选项:

typedef int bool;
#define false 0
#define true 1

参考 http://en.cppreference.com/w/c/string/byte/strstr

【讨论】:

  • 谢谢。效果很好
  • @Kaylo17:不客气!
  • 我不得不稍微改变一下程序以允许我输入我想要的文本。这仍然正确吗?
  • @Kaylo17:据我所知,是的。我的意思是,自从您上次发表评论以来,我还没有更新它。所以,如果它当时对你有用,它现在应该对你有用,因为我从那以后就没有碰过它。 ;)
  • 我本想附上我的代码,但在粘贴之前我按下了回车键。我的错。还是不习惯 Stackoverflow 的布局
【解决方案2】:

这是一个未优化的strstr

char *strstr(char *haystack, char *needle){
if (!needle[0]) return haystack;
unsigned int i;
while (*haystack){
  while (haystack[0]!=needle[0])haystack++;
  i=1;
  while (haystack[i] && needle[i] && haystack[i]==needle[i++]);
  if (!needle[i]) return haystack;
  else haystack+=i;
}
return haystack;
}

或优化版本: http://git.musl-libc.org/cgit/musl/tree/src/string/strstr.c

【讨论】:

    【解决方案3】:

    您想使用函数 strstr 在 c 语言中查找子字符串。例如-

    char s1[] ="hello world";
    char * s2;
    s2 = strstr (str,"world");  // s2 will be null pointer if it is not the substring
                                // else s2 will point to first occurrence of substring
    if(!s2)
       // return true
    else
       // return false
    

    您应该自己尝试弄清楚如何将字符串传递给函数:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-17
      • 1970-01-01
      相关资源
      最近更新 更多