For example I have:
char buff[1000];
I want to search if the string "hassasin" is in that char array. Here is what I have tried.
char word[8] = "hassasin";
char Buffer[1000]=sdfhksfhkasd/./.fjka(hassasin)hdkjfakjsdfhkksjdfhkjh....etc
int k=0;
int t=0;
int len=0;
int sor=0;
for (k=0; k<1000; k++){
for (t=0; t<8; t++){
if (Buffer[k]==word[t]) len++;
if (len==8) "it founds 0.9.1"
}
}
Way 1: Using a Naive Approach Get the string. Create a character array of the same length as of string. Traverse over the string to copy character at the i'th index of string to i'th index in the array.
The strrchr() function finds the last occurrence of c (converted to a character) in string . The ending null character is considered part of the string . The strrchr() function returns a pointer to the last occurrence of c in string . If the given character is not found, a NULL pointer is returned.
std::size_t strlen( const char* str ); Returns the length of the given byte string, that is, the number of characters in a character array whose first element is pointed to by str up to and not including the first null character.
The function strstr returns the first occurrence of a string in another string. This means that strstr can be used to detect whether a string contains another string. In other words, whether a string is a substring of another string.
Yes, you can just use strstr for this:
#include <stdlib.h>
#include <string.h>
char buff[1000];
char *s;
s = strstr(buff, "hassasin"); // search for string "hassasin" in buff
if (s != NULL) // if successful then s now points at "hassasin"
{
printf("Found string at index = %d\n", s - buff);
} // index of "hassasin" in buff can be found by pointer subtraction
else
{
printf("String not found\n"); // `strstr` returns NULL if search string not found
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With