Hi, im trying to create a function that gets two strings , the first string its the source , and the seconed is an understring .
the function should return an int with the value of the position that the understring starts in the source string . so that if ill have thie string as source : "abcdefg" and understring :"efg", than the function should return 5 because "efg" starts at the fifth character of the source string.
i need to do this with array pointers , so any1 has any idea ?

Dani AI

Generated

The core bug in the code posted here is logical: the inner loop increments the two pointers before comparing and returns too early, so partial matches can be reported as full matches (that explains the "testing" / "stupid ..." failure). Decide the index convention up front: your example expects 1-based positions (e = 5 in "abcdefg"), but idiomatic C uses 0-based. Document the choice and the not-found sentinel (commonly -1 for 0-based, or 0 for not found if you return 1-based). already pointed out the early-return issue; correctly suggested the standard strstr if a library call is acceptable; and contributed useful pointers and a snippet.

A compact, pointer-based, corrected implementation (returns a zero-based index, -1 if not found):

/* Return zero-based index of first occurrence, or -1 if not found. */
int underStringPos(const char *haystack, const char *needle)
{
    const char *p, *h, *n;
    if (!haystack || !needle) return -1;
    if (*needle == '\0') return 0; /* empty needle -> match at start */

    for (p = haystack; *p != '\0'; ++p) {
        h = p;
        n = needle;
        while (*n != '\0' && *h == *n) { ++h; ++n; }
        if (*n == '\0') return (int)(p - haystack);
    }
    return -1;
}

Notes and tips: if you must match the original 1-based example, return (index + 1) to callers (or document that callers expect 1-based). Always avoid gets and void main — use fgets and int main(void) and strip the trailing newline. This function is byte-oriented: it counts bytes, not Unicode code points; for UTF-8 text you need a different approach if you care about characters rather than bytes.

For production use prefer the well-tested library strstr (strstr on cppreference). If you need better worst-case performance on long inputs, look into the Knuth-Morris-Pratt algorithm (Knuth-Morris-Pratt algorithm).

Recommended Answers

All 9 Replies

Hi, im trying to create a function that gets two strings , the first string its the source , and the seconed is an understring .
the function should return an int with the value of the position that the understring starts in the source string . so that if ill have thie string as source : "abcdefg" and understring :"efg", than the function should return 5 because "efg" starts at the fifth character of the source string.
i need to do this with array pointers , so any1 has any idea ?

Here you go: http://www.cplusplus.com/strstr
To find the postion using strstr, the sample provided on this page shows you a wat to do it:

Good Luck, LamaBot

Im trying to write my own function that does this with array pointers so there is no point to use an existing function .

So atleast try out something you have in your mind and post it here. Help will automatically ensue..

Im trying to write my own function that does this with array pointers so there is no point to use an existing function .

So? Looking at and understanding an existing function is the way to learn how it's done. Then you can write your own using a similar (not identical) technique.

//

Thanks but i think i got it with out the example ,
This is what ive tried to create ...
ive tried it a couple of times and its seems to work , what do you think
guys ?

#include <stdio.h>
int underStringPos(char *source,char *under)
{
 char *sourceptr = source;
 int counter=0;
 while (*sourceptr){
  if (*sourceptr == *under){
   char *s = sourceptr, *u = under;
   while (*u){
    s++,u++;
    if (*s != *u)
     break;
    return counter;}}
  sourceptr++;
  counter++;}
}
void main()
{
 char str1[40],str2[40];
 int num;
 printf ("Enter main string: ");
 gets(str1);
 printf ("Enter under string: ");
 gets(str2);
 num = underStringPos(str1,str2);
 printf ("UnderStringPos = %d\n",num);}

>what do you think guys?
Your formatting is horried, void main is incorrect, gets is an extremely bad habit, and the algorithm is broken.

Let's start with the formatting. Braces are there for a reason. They tell you when a block starts and when a block ends. However, if you chain the closing braces all on the same line, it doesn't help people who are reading the code[1]. Here's a better format:

int underStringPos(char *source,char *under)
{
  char *sourceptr = source;
  int counter=0;
  while (*sourceptr){
    if (*sourceptr == *under){
      char *s = sourceptr, *u = under;
      while (*u){
        s++,u++;
        if (*s != *u)
          break;
        return counter;
      }
    }
    sourceptr++;
    counter++;
  }
}

Now it's obvious what's nested where and you can more easily follow the flow of execution.

I'll let void main and gets slide, but main returns int, and fgets is much safer than gets.

Now for the logic. Run your program with "testing" and "stupid algorithms are hard to get right". It returns 2 because your loop breaks early. If the first two characters of the substring are matched, the rest of the substring is completely ignored even if it doesn't exist in the source string (exercise: explain why). Perhaps if you return the index when *u is '\0'. That ensures that the loop has run to completion and the entire substring has been matched.


[1] This is a consistent rule of formatting. If you put multiple independent things on one line, that line is more difficult to understand. That's one reason why it's a good idea to put declarations on separate lines even though C lets you put multiple declarations of the same type on one line.

got it , and ive fixed the problem , thanks Narue , and thanks to every1 who tried to help ..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.