943,969 Members | Top Members by Rank

Ad:
  • C Discussion Thread
  • Marked Solved
  • Views: 9253
  • C RSS
You are currently viewing page 1 of this multi-page discussion thread
Dec 10th, 2006
0

Comparing two letters in one string with another char string?

Expand Post »
Hi guys,

This exercise goes as follows:
- Write a function that counts the number of occurences of a pair of letters in a string and another that does the same in a zero-terminated array of char(a C-style string). For example, the pair "ab" appears twice in "xabaacbaxabb".

Now, I found the following solution to the C-style version:
  1. #include <iostream>
  2.  
  3. void compareChar(char *myArr, char *mySecArr);
  4.  
  5. int main()
  6. {
  7. char mychar[] = "xabaacbaxabb";
  8. char letters[2];
  9.  
  10. compareChar(mychar, letters);
  11.  
  12. std::cin.ignore(2);
  13.  
  14. return 0;
  15. }
  16.  
  17. void compareChar(char *myArr, char *mySecArr)
  18. {
  19. int count = 0;
  20.  
  21. std::cout << "Enter two letters to be compaired with the char string 'xabaacbaxabb'" << std::endl;
  22.  
  23. std::cin >> mySecArr;
  24.  
  25. while(strlen(mySecArr) != 2)
  26. {
  27. std::cout << "Wrong amount of letters, try again!" << std::endl;
  28. std::cin >> mySecArr;
  29. }
  30.  
  31. for (int i = 0; myArr[i] != 0; i++)
  32. {
  33. if((myArr[i] == mySecArr[0]) && (myArr[i+1] == mySecArr[1]))
  34. count++;
  35. }
  36.  
  37. std::cout << "The pair '" << mySecArr << "' appears " << count << " time(s) in " << myArr << "." << std::endl;
  38. }

I was wondering if any of you could tell me how I can improve this, the reason for asking is that at the end of the last comparison if((myArr[i] == mySecArr[0]) && (myArr[i+1] == mySecArr[1]))
the myArr[i+1] goes out of bound. Isn't that bad coding?
Similar Threads
Reputation Points: 51
Solved Threads: 4
Posting Pro in Training
JoBe is offline Offline
420 posts
since Sep 2004
Dec 10th, 2006
0

Re: Comparing two letters in one string with another char string?

Anything that goes beyond scope is naughty.
Featured Poster
Reputation Points: 1536
Solved Threads: 431
Posting Expert
iamthwee is offline Offline
5,865 posts
since Aug 2005
Dec 10th, 2006
0

Re: Comparing two letters in one string with another char string?

Jobe, my very first reaction would be, why not write a generic function instead of restricting yourself with search strings of length 2 or 3.
Quote ...
goes out of bound. Isn't that bad coding?
Its not bad coding, its wrong coding. How can you expect your program to perform properly and in the right manner if you are basing your programming logic on computations on areas of memory which don't belong to you ?

Also the trick which you use will soon turn out to be cumbersome if you are asked to do the same with 3 letters, 4 letters, n letters etc.

My thoughts: always look for generic patterns in the problem statement and if they don't incur additional overheads for that case, go ahead and implement them.

For eg here is one implementation which is possible. I haven't tried it but it should pretty much work.
  1. // retuns the last position in the string where the match was found
  2. // modifies the count parameter passed by reference which displays the
  3. // number of times substring occurs.
  4. int my_strstr( const char* str1, const char* str2, int* count )
  5. {
  6. int i = 0 ;
  7. int len1 = strlen( str1 ) ;
  8. int len2 = strlen( str2 ) ;
  9. int pos = 0 ;
  10.  
  11. *count = 0 ; // initialize the counter
  12.  
  13. for( i = 0; i < len1; ++i )
  14. {
  15. if( strncmp( ( str1 + i ), str2, len2 ) == 0 )
  16. {
  17. (*count)++ ;
  18. pos = i ;
  19. }
  20. }
  21. return pos ;
  22. }
  23.  
  24. int main( void )
  25. {
  26. int count ;
  27. char str[] = "ababababa" ;
  28. char search_str[] = "ab" ;
  29. int match = my_strstr( str, search_str, &count ) ;
  30. printf( "The last occurance of \'%s\' was found in \'%s\' at %d.",
  31. str, search_str, match ) ;
  32. printf( "\nThe count of \'%s\' is %d.", search_str, count ) ;
  33. getchar( ) ;
  34.  
  35. return 0 ;
  36. }
You can change the function so that you get it to return the char pointer rather than returning position or you can make the function do both by keeping its prototype as:
char* my_strstr( const char* str1, const char* str2, int* count, int* pos )
which makes the function return char pointer to the substring found as well as modifies the parameters passed to it to reflect the count of substring as well as the position of the last substring.

Hope it helped, bye.
Super Moderator
Featured Poster
Reputation Points: 3233
Solved Threads: 720
Failure as a human
~s.o.s~ is offline Offline
8,872 posts
since Jun 2006
Dec 10th, 2006
0

Re: Comparing two letters in one string with another char string?

Hmmm, well, I came up with this int strLength = strlen(myArr)-1; and then in the loop for (int i = 0; i < strLength; i++) but I see where you're coming from :o

Thanks for the example, I'll see that I can find an equivalent to use in my program next week-end.
Reputation Points: 51
Solved Threads: 4
Posting Pro in Training
JoBe is offline Offline
420 posts
since Sep 2004
Dec 10th, 2006
0

Re: Comparing two letters in one string with another char string?

Click to Expand / Collapse  Quote originally posted by JoBe ...
Hmmm, well, I came up with this int strLength = strlen(myArr)-1; and then in the loop for (int i = 0; i < strLength; i++) but I see where you're coming from :o

Thanks for the example, I'll see that I can find an equivalent to use in my program next week-end.
I would reverse the -1 and go with:
int strLength = strlen(myArr); and for (int i = 0; i < strLength-1; i++)
The reason is strLength actually represents the string length, which you can modify in the loop. And you can still use strLength elsewhere in your program if the need arises. By subtracting 1 first, it's really only useful for this particular part of the program.
Moderator
Reputation Points: 3278
Solved Threads: 894
Posting Sage
WaltP is offline Offline
7,744 posts
since May 2006
Dec 11th, 2006
0

Re: Comparing two letters in one string with another char string?

Click to Expand / Collapse  Quote originally posted by WaltP ...
I would reverse the -1 and go with:
int strLength = strlen(myArr); and for (int i = 0; i < strLength-1; i++)
The reason is strLength actually represents the string length, which you can modify in the loop. And you can still use strLength elsewhere in your program if the need arises. By subtracting 1 first, it's really only useful for this particular part of the program.
Yep, that seems to make better sence, thanks Walt.
Reputation Points: 51
Solved Threads: 4
Posting Pro in Training
JoBe is offline Offline
420 posts
since Sep 2004
Dec 16th, 2006
0

Re: Comparing two letters in one string with another char string?

Hi guys,

Solved the exercise, but, I'm not that happy with it because both functions actually look very similar, meaning, the c-style string and the cpp string. Don't think that was the idea of this exercise.

  1. //Exercises from the book: The C++ Programming Language by Bjarne Stroustrup.
  2.  
  3. /*Write a function that counts the number of occurences of a pair of letters in a string and
  4.   another that does the same in a zero-terminated array of char(a C-style string). For example,
  5.   the pair "ab" appears twice in "xabaacbaxabb".
  6.   */
  7.  
  8. #include <iostream>
  9. #include <string>
  10.  
  11. int compareChar(char *myArr, char *mySecArr);
  12. int compareString(std::string myWord, char mySecArr[2]);
  13.  
  14. int main()
  15. {
  16. char mychar[] = "xabaacbaxabba";
  17. char letters[2];
  18. std::string myWord;
  19.  
  20. myWord = mychar;
  21.  
  22. std::cout << "Enter two letters to be compaired with the char string '" << mychar << "'" << std::endl;
  23.  
  24. std::cin >> letters;
  25.  
  26. int count = compareChar(mychar, letters);
  27. std::cout << "The pair '" << letters << "' appears " << count << " time(s) in " << mychar << "." << std::endl;
  28.  
  29. std::cout << "Enter another two letter to be compaired with the string string '" << myWord << "'" << std::endl;
  30.  
  31. std::cin >> letters;
  32.  
  33. count = compareString(myWord, letters);
  34. std::cout << "The pair '" << letters << "' appears " << count << " time(s) in " << myWord << "." << std::endl;
  35.  
  36. std::cin.ignore(2);
  37.  
  38. return 0;
  39. }
  40.  
  41. int compareChar(char *myArr, char *mySecArr)
  42. {
  43. int count = 0;
  44.  
  45. for (int i = 0; i < strlen(myArr)-1; i++)
  46. {
  47. if((myArr[i] == mySecArr[0]) && (myArr[i+1] == mySecArr[1]))
  48. count++;
  49. }
  50.  
  51. return count;
  52. }
  53.  
  54. int compareString(std::string myWord, char mySecArr[2])
  55. {
  56. int count = 0;
  57.  
  58. for (int i = 0; i < myWord.size()-1; i++)
  59. {
  60. if ((myWord[i] == mySecArr[0]) && (myWord[i+1] == mySecArr[1]))
  61. count++;
  62. }
  63.  
  64. return count;
  65. }

Is there a better way to compare a character array with a cpp string?
Reputation Points: 51
Solved Threads: 4
Posting Pro in Training
JoBe is offline Offline
420 posts
since Sep 2004
Dec 16th, 2006
0

Re: Comparing two letters in one string with another char string?

Maybe the C++ version was supposed to use .find()?

This is enough room for one character plus the terminating null:
char letters[2];
Team Colleague
Reputation Points: 2780
Solved Threads: 312
long time no c
Dave Sinkula is offline Offline
4,790 posts
since Apr 2004
Dec 16th, 2006
0

Re: Comparing two letters in one string with another char string?

Click to Expand / Collapse  Quote originally posted by JoBe ...
Is there a better way to compare a character array with a cpp string?
There are other ways, but not necessarily better. For just two characters yours way is efficient. If you had to test 4 or more, a loop might be better.

There are also the C-string str???() functions and C++ strings compare methods. Either of those you can look into.
Moderator
Reputation Points: 3278
Solved Threads: 894
Posting Sage
WaltP is offline Offline
7,744 posts
since May 2006
Dec 17th, 2006
0

Re: Comparing two letters in one string with another char string?

Maybe the C++ version was supposed to use .find()?
HI Dave, long time no see, I see you lost your mod stick, good to see you here again though

I tried using .find() and .compare(), but it seems that they can only be used to find if there is A resemblance of code in both strings, not several. Could it be that I have to write it in a way it traverses threw the string that I want to compare? If so, I can only traverse threw one by using a loop and either string[i] or *(string + i) right ?

Quote ...
This is enough room for one character plus the terminating null:
char letters[2];
DARN, I forgot the terminating null, it does work though, I'll change it to [3] and add the '\0' at the back, thanks for the tip.


Click to Expand / Collapse  Quote originally posted by WaltP ...
There are other ways, but not necessarily better. For just two characters yours way is efficient.
Oh, ok, thanks.

Quote ...
If you had to test 4 or more, a loop might be better.
Nope, don't understand that, I thought I was using a loop?

Quote ...
There are also the C-string str???() functions and C++ strings compare methods. Either of those you can look into.
Thought so, thing is, as said above, how do I use .find() and/or .compare() when having to go threw the whole string when trying to find more then one occurence of the same piece of string?
Reputation Points: 51
Solved Threads: 4
Posting Pro in Training
JoBe is offline Offline
420 posts
since Sep 2004

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C Forum Timeline: sending values to functions
Next Thread in C Forum Timeline: matrix transpose





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC