vendredi 11 décembre 2020

How to iterate through array to find C-style string

Write a function, char* findx(const char* s, const char* x), that finds the first occurrence of the C-style string x in s. Do not use any standard library functions. Do not use subscripting; use the dereference operator * instead.

For my current purposes, I'm using the constraints of the prompt rather loosely. What I currently have is very rough code to find the occurrence of the string, but I'm having trouble with pointer arithmetic to be able to output the matching word. Because of the way I constructed my for loop, the output omits the first letter. Furthermore, I'm using a variable outside my for loop to increment my pointer, which I want to avoid. Any ideas on how I can improve this? I know there's better ways to approach this, but I wanted to see if I can improve this without significantly altering the for loop.

const char* findx(const char* s, const char* x)
{
  int size = strlen(s);
  int size1 = strlen(x);
  int n = 1;

  for (const char* p = &s[0]; p < &s[size]; ++p) {
    if (*p == *x) {
      for (const char* j = &x[1]; j < &x[size1]; ++j) {
        if (*j == *(p+n)) {
          cout << *j;
          ++n;
        }
    }
   }
  }
  return nullptr;
}

Aucun commentaire:

Enregistrer un commentaire