-1

I was wondering if there is a way to look for a substring in a char* array.

I can't seem to find an equivalent of Contains() from Java for C

For example:

char *buff = "this is a test string. The string contains random text.";

suppose I input the substring to compare to buff and see how many times is substring found in buff.

I am able to find the first occurrence but having issues with multiple occurrences. Can someone assist me?

user3353723
  • 221
  • 1
  • 7
  • 15
  • So what exactly you don't understand then? The obvious thing is to restart the search after the first position you have found. If you don't know to do that it is time to revise (1) how arrays and strings work in C, (2) how iteration statements work in C. – Jens Gustedt Oct 07 '14 at 08:25
  • Hi all, suppose I have a `char* random` with values `ABCDSDGHFG` and I want to extract a substring based on 2 index values, how would I retrieve that? Basically something similar to java that would do the following: `substring(2, 5)` – user3353723 Oct 07 '14 at 08:26

2 Answers2

3

There is a standard C library function called strstr which does substring searches:

#include <string.h>

char *strstr(const char *haystack, const char *needle);

The strstr() function finds the first occurrence of the substring needle
in the string haystack.  The terminating null bytes ('\0') are not compared.
isedev
  • 18,848
  • 3
  • 60
  • 59
  • how to find multiple occurrence? – user3353723 Oct 07 '14 at 08:12
  • 1
    Well, you can use the start of the first substring match and the length of the substring itself to calculate a new starting point for a subsequent substring search. Or, if the substring can match itself, simply start a new search one character after the last result. – isedev Oct 07 '14 at 08:13
  • Does `Contains` return multiple occurrences in Java then? – Jongware Oct 07 '14 at 08:19
  • Hi all, suppose I have a `char* random` with values `ABCDSDGHFG` and I want to extract a substring based on 2 index values, how would I retrieve that? Basically something similar to java that would do the following: `substring(2, 5)` – user3353723 Oct 07 '14 at 08:20
  • @isedev yes you are correct about the Contains method – user3353723 Oct 07 '14 at 08:21
1

Such a function is named strstr and declared in header <string.h>

From the C Standard

7.23.5.7 The strstr function Synopsis 1

#include <string.h>
char *strstr(const char *s1, const char *s2);

Description 2 The strstr function locates the first occurrence in the string pointed to by s1 of the sequence of characters (excluding the terminating null character) in the string pointed to by s2.

Returns 3 The strstr function returns a pointer to the located string, or a null pointer if the string is not found. If s2 points to a string with zero length, the function returns s1.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335