| | |
Comparing two letters in one string with another char string?
Thread Solved |
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:
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
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:
C Syntax (Toggle Plain Text)
#include <iostream> void compareChar(char *myArr, char *mySecArr); int main() { char mychar[] = "xabaacbaxabb"; char letters[2]; compareChar(mychar, letters); std::cin.ignore(2); return 0; } void compareChar(char *myArr, char *mySecArr) { int count = 0; std::cout << "Enter two letters to be compaired with the char string 'xabaacbaxabb'" << std::endl; std::cin >> mySecArr; while(strlen(mySecArr) != 2) { std::cout << "Wrong amount of letters, try again!" << std::endl; std::cin >> mySecArr; } for (int i = 0; myArr[i] != 0; i++) { if((myArr[i] == mySecArr[0]) && (myArr[i+1] == mySecArr[1])) count++; } std::cout << "The pair '" << mySecArr << "' appears " << count << " time(s) in " << myArr << "." << std::endl; }
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? 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.
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.
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:
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.
•
•
•
•
goes out of bound. Isn't that bad coding?
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.
c Syntax (Toggle Plain Text)
// retuns the last position in the string where the match was found // modifies the count parameter passed by reference which displays the // number of times substring occurs. int my_strstr( const char* str1, const char* str2, int* count ) { int i = 0 ; int len1 = strlen( str1 ) ; int len2 = strlen( str2 ) ; int pos = 0 ; *count = 0 ; // initialize the counter for( i = 0; i < len1; ++i ) { if( strncmp( ( str1 + i ), str2, len2 ) == 0 ) { (*count)++ ; pos = i ; } } return pos ; } int main( void ) { int count ; char str[] = "ababababa" ; char search_str[] = "ab" ; int match = my_strstr( str, search_str, &count ) ; printf( "The last occurance of \'%s\' was found in \'%s\' at %d.", str, search_str, match ) ; printf( "\nThe count of \'%s\' is %d.", search_str, count ) ; getchar( ) ; return 0 ; }
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.
I don't accept change; I don't deserve to live.
•
•
•
•
Hmmm, well, I came up with thisint strLength = strlen(myArr)-1;and then in the loopfor (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.
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.
The 3 Laws of the Procrastination Society:
1) Never do today that which can be put off until tomorrow
2) Tomorrow never comes
1) Never do today that which can be put off until tomorrow
2) Tomorrow never comes
•
•
•
•
I would reverse the -1 and go with:
int strLength = strlen(myArr);andfor (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.
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.
Is there a better way to compare a character array with a cpp string?
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.
C Syntax (Toggle Plain Text)
//Exercises from the book: The C++ Programming Language by Bjarne Stroustrup. /*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". */ #include <iostream> #include <string> int compareChar(char *myArr, char *mySecArr); int compareString(std::string myWord, char mySecArr[2]); int main() { char mychar[] = "xabaacbaxabba"; char letters[2]; std::string myWord; myWord = mychar; std::cout << "Enter two letters to be compaired with the char string '" << mychar << "'" << std::endl; std::cin >> letters; int count = compareChar(mychar, letters); std::cout << "The pair '" << letters << "' appears " << count << " time(s) in " << mychar << "." << std::endl; std::cout << "Enter another two letter to be compaired with the string string '" << myWord << "'" << std::endl; std::cin >> letters; count = compareString(myWord, letters); std::cout << "The pair '" << letters << "' appears " << count << " time(s) in " << myWord << "." << std::endl; std::cin.ignore(2); return 0; } int compareChar(char *myArr, char *mySecArr) { int count = 0; for (int i = 0; i < strlen(myArr)-1; i++) { if((myArr[i] == mySecArr[0]) && (myArr[i+1] == mySecArr[1])) count++; } return count; } int compareString(std::string myWord, char mySecArr[2]) { int count = 0; for (int i = 0; i < myWord.size()-1; i++) { if ((myWord[i] == mySecArr[0]) && (myWord[i+1] == mySecArr[1])) count++; } return count; }
Is there a better way to compare a character array with a cpp string?
Maybe the C++ version was supposed to use
This is enough room for one character plus the terminating null:
.find()?This is enough room for one character plus the terminating null:
char letters[2]; "One of the methods used by statists to destroy capitalism consists in establishing controls that tie a given industry hand and foot, making it unable to solve its problems, then declaring that freedom has failed and stronger controls are necessary." --Ayn Rand
•
•
•
•
Is there a better way to compare a character array with a cpp string?
There are also the C-string
str???() functions and C++ strings compare methods. Either of those you can look into. The 3 Laws of the Procrastination Society:
1) Never do today that which can be put off until tomorrow
2) Tomorrow never comes
1) Never do today that which can be put off until tomorrow
2) Tomorrow never comes
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 ?
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.
Oh, ok, thanks.
Nope, don't understand that, I thought I was using a loop?
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?
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 ?
•
•
•
•
This is enough room for one character plus the terminating null:
char letters[2];
•
•
•
•
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.
![]() |
Similar Threads
- Palindrome Help Please :) (C++)
- String conversion... (C++)
- Elementry C++.. little help for mods (C++)
- broken code (C++)
- String class help (Java)
- MIPS - I'm Not getting the right answer :( Can anybody Review :) (Assembly)
- I need help (C++)
- Need some help with a Java lab... (Java)
Other Threads in the C Forum
- Previous Thread: sending values to functions
- Next Thread: matrix transpose
| Thread Tools | Search this Thread |
#include * adobe ansi api array asterisks binarysearch centimeter changingto char character cm copyimagefile cprogramme creafecopyofanytypeoffileinc createcopyoffile csyntax database directory dynamic feet fgets file fork frequency function getlasterror getlogicaldrivestrin givemetehcodez global grade graphics gtkgcurlcompiling gtkwinlinux hacking highest histogram include incrementoperators infiniteloop input interest kernel keyboard kilometer linked linkedlist linux linuxsegmentationfault list locate logical_drives looping loopinsideloop. lowest match matrix meter microsoft mqqueue mysql number odf opendocumentformat owf pattern pdf performance pointer posix probleminc process program programming radix recursion recv repetition research reversing scanf segmentationfault sequential shape single socket socketprograming standard string systemcall threads turboc unix user voidmain() wab whythiscodecausesegmentationfault windows.h windowsapi






