- #1
yungman
- 5,718
- 241
I am working on the part of the program that I want to search through a vector of structure that has c-string(last name) as member. I decide NOT to search the complete string because I want to avoid in case someone spell the last name wrong and fail to find a match. So I want to search only the first character or the first two characters for matching only.
There lies the problem, It's easy to do string compare strcmp( string1, string2) =0 to find match. But I need to get the first one or two character out for comparison. I don't know an easy way to extract the first two characters out for comparison. It used to have strncpy(str1, str2, 2) to copy the first two characters out. BUT sadly VS flag error and insists on using strncpy_s(). strncpy_s() will not allow copy from a long string to a short one to truncate out the rest.
Of cause, I can use loop to copy out a character at a time. But that seems stupid. Is there an elegant way to compare the first two characters.
For example, if I search for "ch", I want to find last names like "chan", "chang", "chen", "chin", "chu" etc. Don't laugh, these are all REAL Chinese last names. I don't want anyone to miss "chen" if one typed in "chan" because both sound exactly the same in Chinese. It's an easy mistake.
Thanks
Last resort is
There lies the problem, It's easy to do string compare strcmp( string1, string2) =0 to find match. But I need to get the first one or two character out for comparison. I don't know an easy way to extract the first two characters out for comparison. It used to have strncpy(str1, str2, 2) to copy the first two characters out. BUT sadly VS flag error and insists on using strncpy_s(). strncpy_s() will not allow copy from a long string to a short one to truncate out the rest.
Of cause, I can use loop to copy out a character at a time. But that seems stupid. Is there an elegant way to compare the first two characters.
For example, if I search for "ch", I want to find last names like "chan", "chang", "chen", "chin", "chu" etc. Don't laugh, these are all REAL Chinese last names. I don't want anyone to miss "chen" if one typed in "chan" because both sound exactly the same in Chinese. It's an easy mistake.
Thanks
Last resort is
C++:
#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
int main()
{ int i;
char shortA[3], longA[] = "chang";
for (i = 0; i < 2; i++)
shortA[i] = longA[i];
shortA[i] = NULL;
cout << shortA << "\n\n";
return 0;
}
Last edited: