Search in substring Problem

Hello everybody!

I am trying to make a function which finds the position of a substring in a char pointer and I have a problem: it doesn't return the right position but the "word" string contains bad characters. For example, for 'strfnd("Hello everybody!","everybody")' it returns 0. I am trying as much I can to avoid the string class. Here is my code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
int length(char* str) // Used to return the string length
{
    size_t sz=0;
    while(str[sz]!='\0')
        sz++;
    return sz;
}
int strfnd(char* str,char* substr)
{
    char word[length(substr)];
    for(int i=0;i<length(str)-length(substr)+1;i++)
    {
        for(int x=0;x<length(substr);x++)
            word[x]=str[i+x];
        cout<<'\r';
        if(strcmp(substr,word)==0)return i;
    }
    return -1;
}

Please tell me why doesn't it work without "cout".

Thanks in advance.
Last edited on
char word[length(substr)]; is not ISO standard C++. Static array sizes must be determined at compile time. Instead you could try dynamically allocating memory.
http://www.cplusplus.com/doc/tutorial/dynamic/

Please tell me why doesn't it work without "cout".

Probably because the compiler generated a section of code that somehow "accidentally" had memory available for char word[]

Pro Tip: You do not need to create a new array in this function. Because you could just increment the haystack pointer.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
bool prefix_match(char *astr, char*bstr) {
    while(*astr != '\0' && *bstr != '\0') {
        if(*astr != *bstr) { return false; }
        ++astr; ++bstr;
    }
    return true;
}
int strfnd(char *haystack, char *needle) {
    size_t i = 0;
    while(*haystack != '\0') {
        if(prefix_match(haystack, needle)) { return i; }
        ++i; ++haystack;
    }
    return -1;
}
Now it works. I understand what's wrong with my code.
Thank you very much kevinkjt2000 for help.
Last edited on
The problem with your original code was that you didn't null-terminate word.

I am trying as much I can to avoid the string class.

For what it's worth, strstr() will do what you want. It's part of the C library.
Nope, I don't like using substr() because it returns a string, not its position.
Last edited on
By substr() I assume you mean strstr() which does indeed return the position of the found substring. If you need an integer index all you need to do is a bit of pointer arithmetic foundPointer - originalPointer
https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BitOp/pointer.html

Also here is a link to a strstr() example:
http://www.cplusplus.com/reference/cstring/strstr/
Last edited on
Topic archived. No new replies allowed.