• C

Is there a Function in C Similar to IndexOf in .NET?

Thank you so much,


Jazon.net
LVL 3
piratepatrolAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Harisha M GEngineerCommented:
Hi piratepatrol,
    No. C doesn't support objects at all (ANSI C)

Bye
---
Harish
ozoCommented:
#include <string.h>

char *strstr(const char *big, const char *little);
Harisha M GEngineerCommented:
OOPs... I thought something else. Sorry :(

Yes... ozo is right...

x = strstr("abcdef","cd");

will return 2 (Remember that the indexing starts from 0)
Your Guide to Achieving IT Business Success

The IT Service Excellence Tool Kit has best practices to keep your clients happy and business booming. Inside, you’ll find everything you need to increase client satisfaction and retention, become more competitive, and increase your overall success.

piratepatrolAuthor Commented:
I just found strstr in an online tutorial.

mgh_mgharish, strstr returns a pointer - how did you make it return 2?
Harisha M GEngineerCommented:
Here is the function required....

int indexof(const char *str,const char *sub)
{
  int i,j;
  for(i=0;str[i]!='\0';i++)
  {
    for(j=0;str[j+i]==sub[j];j++)
    {
      if(sub[j]=='\0')
        return i;
      if(str[j+i]=='\0')
        return -1;
    }
    if(j!=0 && sub[j]==0)
      return i;
  }
  return -1;
}

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Harisha M GEngineerCommented:
I am not sure whether the logic of the program is correct or not... but few points...

Maintain neat code with indentation so that it becomes easy for the reader and for you too while debugging.
You have assingned the pressed key to 'option' but the return value is 'choice'.


Here is a modified code. Check and ask if you have any doubts :)



#include <conio.h>       //required for getch()
#include <iostream.h>    //required for cin and cout
#include <stdio.h>

void instructions (void);
void playgame (void);
void matrix(void);
int menu (void);

//Main() is where program execution starts
void main (void)
{
      int choice = 0;

      char key;  //define a character called key
      do
      {
            choice = menu();
            clrscr();

            if(choice == 1)
                  instructions();
            else if (choice == 2)
                  playgame();

      }while (choice != 3);
      
      clrscr();
}

int menu (void)
{
      int option = 0;
      char key;
      clrscr();
      cout << "\n\n\n\n\n\n\t\t\t\tTIC TAC TOE\n\n\n\t\t";
      cout << "Think You Can Win a Game of Tic Tac Toe?\n\n\n\t\t";
      cout << "Please choose one of the following options...\n\n\n";
      cout << "\n\tView Instructions     Press '1'";
      cout << "\n\tStart New Game      Press '2'";
      cout << "\n\tExit Program           Press '3'";

      do
      {
            key= getch();                                   //input choice
      }while (key!='1' && key!='2' && key!='3');


      if (key=='1') option = 1;
      if (key=='2') option = 2;
      if (key=='3') option = 3;

      return choice;
}

void instructions (void)
{
      cout << "\n\n\tThe object of the game is to get 3 matching symbols in a row";
}

void playgame (void)
{
      clrscr();
      hline(5,10,17,4); //we call the function here
      hline(5,16,17,4);
      vline(10,5,17,4);
      vline(16,5,17,4);
}
Harisha M GEngineerCommented:
Sorry.. it was for another question.. :(
Fernando SotoRetiredCommented:
If strstr is successful it will return a pointer to the first occurrence of string2 as a substring of string1. If the search fails it returns a NULL.

chr* strstr(const char* string1, const char* string2)

So in the above example from mgh_mgharish

x = strstr("abcdef","cd");

Returns a pointer to the first "c" in "abcdef" which is character postion 2 because it is a zero base index.
Harisha M GEngineerCommented:
piratepatrol, incidentally there is no built-in IndexOf() function in C.

So I wrote one myself and have given.
Harisha M GEngineerCommented:
Instead of my function, you can also use

x = (int) strstr(str,sub) - (int) str;

which will return 2 only (int). But it is not a good way :)
Fernando SotoRetiredCommented:
Or another way

      char string1[] = "abcdefg";
      char string2[] = "cd";
      char* retString = NULL;
      int pos = 0;

      retString = strstr(string1, string2);
      pos = retString - string1;
Fernando SotoRetiredCommented:
The variable pos will also have a value of 2

     retString = strstr(string1, string2);
     pos = retString - string1;
Harisha M GEngineerCommented:
FernandoSoto, that is what I did. But it is better to cast them to the int type while subtracting :)
ozoCommented:
You may want to check that retString is not NULL before subtracting string1
Fernando SotoRetiredCommented:
Hi mgh_mgharish

the use of the following statement is valid

pos = retString - string1;

Where string1 and retString are pointer to the same type. This is known as Pointer Arithmetic and do not need to be cast. In fact casting them can cause errors. For example if you have a pointer to structure of lets say 80 bytes and we have an array of these structures. So to go from one structures to the next requiers the pointer to increment by 80 bytes each time. So lets say the pointer is pointing to memory address 3000 so the start of the next struct will be 3080. Therefore if x is a pointer to the first of these structures and pos is an integer

pos = (int) x + 1; will point to memory address 3001 which is the first byte into the first structure

where

pos = x + 1; will be pointing to the start of the second structure or at memory 3080.


Fernando SotoRetiredCommented:
Thank you for catching that ozo;
aib_42Commented:
>     retString = strstr(string1, string2);
>     pos = retString - string1;
...
>x = (int) strstr(str,sub) - (int) str;
...

I would just do:

char *target;

target = strstr(lookfor, mainstr);

if (target == NULL) return -1; /* (what does IndexOf return if it can't find anything?) */

else return (unsigned int)(target-mainstr);

(Actually I would do (((target=strstr(lookfor,mainstr))==NULL)?(-1):(unsigned int)(target-mainstr)) but that's irrelevant :)

What's relevant is C has a single type of pointer arithmetic: subtraction, which returns a value of type ptrdiff_t. That would be a much better solution than converting the pointers to integers, which is more troublesome.
piratepatrolAuthor Commented:
You guys are awesome!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.