Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search a string in a char array in C? [closed]

Tags:

arrays

c

string

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" 
    } 
}
like image 544
hassasin Avatar asked Nov 19 '12 09:11

hassasin


People also ask

How do I find a string in a character array?

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.

How do you check if the character is the end of a string in C?

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.

Can I use strlen with char * array?

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.

How do you check if a word is present in a string in C?

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.


1 Answers

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
 }
like image 95
Paul R Avatar answered Oct 19 '22 07:10

Paul R