Thread: Search a give char in a string

  1. #1
    Registered User alice's Avatar
    Join Date
    Mar 2004
    Posts
    36

    Search a give char in a string

    Help, my program is to search a alphabet in a list of string, and return the postition, if not found return with -1.
    What's is doing wrong of my code?
    ie. should return '7' of 'h'.

    thk a alot.

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    
    int firstIndex(char* str, char aChar) {
     
     int i,length;
     length=100;
    
    for (i=0;i>=length ;i++ )
     if (str[i]==aChar)
    	return i;             
      else
    	return -1;  /* If can't found */
    
    }
    
    void main() {
    
      char  aChar='h';
      int index;
      char* str[99]={"a","b","c","d","e","f","g","h","i","j","k","l","m"};
    
      index=firstIndex(str,aChar);
    
      printf("The char is in position %d\n",index);
    
      getchar();
    
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Does it even compile without warnings?
    The parameter you pass to the function is completely wrong.

    > length=100;
    How about length = strlen(str);
    Then you check only the chars which are valid

    > for (i=0;i>=length ;i++ )
    You mean LESS THAN

    > void main() {
    I and others have told you this is wrong several times now.
    Are you just ignoring what is said?

    > char* str[99]={"a","b","c","d","e","f","g","h","i","j","k","l", "m"};
    This is many short strings, not one long string
    char str[]={"abcdefghijklm"};
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Yes, my avatar is stolen anonytmouse's Avatar
    Join Date
    Dec 2002
    Posts
    2,544
    Code:
    for (i=0;i>=length ;i++ )
     if (str[i]==aChar)
    	return i;             
      else
    	return -1;
    You only want to return -1 once the loop has finished and every character has been checked.
    Code:
    for (i = 0;i < length;i++ )
    {
        if (str[i]==aChar) return i;
    }
    
    return -1;

  4. #4

    Post

    Hello,

    I do see alot of problems with this code. Nothing to major, its mainly your firstIndex() code that looks wrong. I fixed a few bugs:

    Code:
    int firstIndex(char **str, char aChar) {	// Fix: **str
    	int i, length;
    	length = 100;
    
    	for (i = 0; i <= length; i++ ) {	// Fix: <= length
    		if (str[i][0] == aChar)	// Fix: str[i][0]
    			return i;    
    	}
    
    	return -1;  /* If can't found */
    }
    Code 1.1: firstIndex() fixed

    Alright, here is what I did. Since you have *str[99] you need to send the pointer to your function. For example, **str in the first argument because you decided to make each letter in your main string a block of text. Another way you could have done this, if you did not need each letter to represent its own string is something like:

    char str[99]={ 'a','b','c','d','e','f','g','h','i','j','k','l','m ','n','o','p','q','r','s','t','u','v','w','x','y', 'z' };
    Then you could set the first argument of firstIndex() to "char *str" since str[0] would equal 'a', but in your case str[0][0] = 'a', remember because you have a char* [] which means the first [] is the string and the second [] is the first character of your string.

    Example:

    char *str1 = {"Hello"};
    char *str2[2] = {"Hi", "Bye"};

    printf("%c\n", str1[0]); // show first char of *str
    printf("%c\n", str2[0][0]); // show first char of *str[0] ("Hi")
    Hope that makes sense.

    Also when using "return i", you only have to do it if the case was found, else every function needs a main return and using the else doesn't define that, so I just set it to return -1 at the end. If the case was found, it'll return right there and never make it to -1, so either way it will return i or -1, but this way is safer.

    Most of all, thanks to Salem, you need to use <= to increment i, else your for loop wont go anywhere, example:

    Increment i if i is greater than or equal to length.

    Well, that will not move, as long as length is at 100 and i is at 0. So if 0 is not greater than or equal to 100, don't increment. Else what we want to do is increment 0 as long as it is less than or equal to 100, saying it will increment

    So now just replace your code firstIndex() with Code 1.1's example, and tell me how it goes.

    Hope this helps,
    - Stack Overflow
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >// Fix: **str
    Granted, that's a valid fix, but I don't think it was what the OP was trying for.

    >// Fix: <= length
    This isn't a fix, it's a bug. First: arrays are zero based in C. That means 0 to n - 1, not 0 to n. Second: length is off by one to begin with, you just make the fencepost error even worse by being off by two.

    >// Fix: str[i][0]
    Once again, I don't really think this is what the OP was going for. Perhaps something more like this:
    Code:
    #include <stdio.h>
    
    int firstIndex(char *str, char aChar) {
      int i;
    
      for (i = 0; str[i] != '\0'; i++ ) {
        if (str[i] == aChar)
          return i;    
      }
    
      return -1;  /* If can't found */
    }
    
    int main(void) {
    
      char  aChar='h';
      int index;
      char str[] = "abcdefghijklm";
    
      index=firstIndex(str,aChar);
    
      printf("The char is in position %d\n",index);
    
      getchar();
      return 0;
    }
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 04:13 PM
  2. String Manipulation problems -_-
    By Astra in forum C Programming
    Replies: 5
    Last Post: 12-13-2006, 05:48 PM
  3. newbie needs help with code
    By compudude86 in forum C Programming
    Replies: 6
    Last Post: 07-23-2006, 08:54 PM
  4. String Class Operations
    By Aidman in forum C++ Programming
    Replies: 10
    Last Post: 04-06-2003, 02:29 PM
  5. "Operator must be a member function..." (Error)
    By Magos in forum C++ Programming
    Replies: 16
    Last Post: 10-28-2002, 02:54 PM