How to search just the first two characters in a c-string?

  • Thread starter yungman
  • Start date
  • Tags
    Search
In summary, the conversation discusses the use of strncmp() in order to compare the first two characters of two c-strings. This function is not commonly known and was not mentioned in the book the person was using. They also mention the possibility of using loop to compare characters one by one, but this is deemed inefficient. Other suggestions for searching include looking for C string functions or using national language support for better handling of international character sets.
  • #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
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:
Technology news on Phys.org
  • #3
yungman said:
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.

For an interesting coding exercise in addressing this issue you may consider implementing the Soundex algorithm.
 
  • Like
Likes jedishrfu
  • #4
jedishrfu said:
Theres two ways:

strncmp or manually via a simple if statement comparing each character.

https://www.geeksforgeeks.org/stdstrncmp-in-c/
Thank you so much. strncmp() works. It's NOT in the book! The book only has strcmp().
C++:
//experiment copying c-strings
#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
int main()
{    char shortA[3], longA[] = "chang";
    char more;
    do
     {    
        cout << " Type first two character of the name to search: ";
        cin.getline(shortA, 3); cout << "\n\n";
        int comp = strncmp(shortA, longA, 2);
        if(comp > 0) cout << " The name you enter is greater than 'ch' ";
        if (comp ==0) cout << " The name you enter is equal to 'ch' ";
        if (comp < 0) cout << " The name you enter is smaller than 'ch' ";
        cout << "\n\n";
        cout << " You want to do it again? "; 
        
         cin.get(more); cout << "\n\n";
        cin.ignore();
     }while(more == tolower('y'));
    return 0;
}
thanks
 
  • #6
jedishrfu said:
Ahh but it’s in the book of Google. :-)
Only if you know what you are looking for. When I typed "compare first two characters of two c-strings" nothing came up that was relevant. I did not know strncmp() exist.
 
  • #7
yungman said:
When I typed "compare first two characters of two c-strings" nothing came up that was relevant.
Come on. Use your imagination. What if you searched "C string functions"?

Or inventing and writing your own function that does what strncmp does?
 
  • Like
Likes Klystron and Vanadium 50
  • #8
yungman said:
Only if you know what you are looking for. When I typed "compare first two characters of two c-strings" nothing came up that was relevant. I did not know strncmp() exist.

strncmp is the second hit for me when I search for this (I did not include quotes).
 
  • Like
Likes Vanadium 50
  • #9
yungman said:
Thank you so much. strncmp() works. It's NOT in the book!
Something better than doing a web search is looking at the documentation. If you're working with C-strings, you should look at the functions declared in the cstring header (AKA string.h).
strncmp is listed in http://cplusplus.com/reference/cstring/
 
  • Like
Likes yungman and Vanadium 50
  • #10
To be fair, your google search experience may be different from mine considering I search for software related stuff a lot. Google does optimize searches to favor your preferences while making sure you see what they want you to see in your region of the world and even country.

Also string functions while ubiquitous in C programs are not the best at handling international character sets like UTF- 8 in string processing for that there are other functions better suited to national language support.
 
  • Like
Likes yungman
  • #11
jedishrfu said:
To be fair, your google search experience may be different from mine considering I search for software related stuff a lot. Google does optimize searches to favor your preferences while making sure you see what they want you to see in your region of the world and even country.

Also string functions while ubiquitous in C programs are not the best at handling international character sets like UTF- 8 in string processing for that there are other functions better suited to national language support.
Exactly, If I search on electronic design, it's SO EASY because I am in all your shoes when comes to electronics and I was one of the people that advice in the EE forum here 10 years ago. That's why I racked up over 4000 posts here. I am sure I would tell students that ask about EE why don't you google!

Even if I don't know that specific topic in EE, I know enough what to look for. The key is I am new in C++, that's the reason at the beginning a few months ago, it's almost USELESS to google as even if I find something, it looked like Russian to me. AND I was being accused here " why don't you google"! Believe me, I always did first. It's getting a lot better now that I studied 13 chapters and know the terms a lot better than before.
 
  • #12
Mark44 said:
Something better than doing a web search is looking at the documentation. If you're working with C-strings, you should look at the functions declared in the cstring header (AKA string.h).
strncmp is listed in http://cplusplus.com/reference/cstring/
I keep forgetting the book I use is 10 years old! strncmp is not around, neither strncpy_s and all that. That's the only version I can get the pdf file. Not only it's free, more importantly, I can print out and separate into like 10 page each so I can lie down and read because of my neck. It's very hard to lie down and hold the big book to read! Now I have to use another Gaddis book soon ( not the brief edition) to study chapter 16 to 20, I can't get the pdf. I am actually thinking about cutting the book apart to very thin sections so I can read lying down.
 
  • #13
I believe all the C string functions were there since like forever ie circa 1980 and earlier.

This is because C++ folks had to convince C folks to use the language. The earliest C++ was a translator on top of C ie C++ got translated to C and then compiled by C and then loaded by the loader.
 
  • Like
Likes Klystron
  • #14
jedishrfu said:
I believe all the C string functions were there since like forever ie circa 1980 and earlier.

Indeed. I used strncmp and other length-guarded string functions in the late 80-ties. A look at the old strncmp(3) man page indicate it standard-wise was around at least in C89 (ANSI C), and the function is also mentioned in my copy of "The UNIX Programming Environment" by Kerninghan and Pike in 1984, that is before ANSI C. However, I don't see it mentioned in the 1978 "The C Programming Language" by Kerninghan and Ritchie.
 
  • #15
Filip Larsen said:
I used strncmp and other length-guarded string functions in the late 80-ties.

I checked - it's not in K&R. (1st edition - but it is in the 2nd)

I have code from December of 1984 that used strncmp.
 
  • Like
Likes Klystron and Filip Larsen
  • #16
jedishrfu said:
I believe all the C string functions were there since like forever ie circa 1980 and earlier.
That's not the case with strcpy_s, strcat_s, strncpy_s, and a number of other string functions that are more secure (reflected by the appended _s in their names). These were added in the C11 standard, I believe.
 
  • Like
Likes jedishrfu
  • #17
Mark44 said:
That's not the case with strcpy_s, strcat_s, strncpy_s, and a number of other string functions that are more secure (reflected by the appended _s in their names). These were added in the C11 standard, I believe.
I think those functions are still `"optional", in that they are not required to be implemented. There was talk about adding them as a core feature in c++17, but I guess not. It still isn't part of glibc. I found this out when I tried to compile one of Yungmans programs. It's been a while since I googled the best way to copy c-strings. It's amazing how much disagreement there is about it. Seems snprintf is popular. I think you can securely use any of them.
 
Last edited:
  • #18
I checked and strncmp is not in Lattice C v1.0 (1982) but was available (probably from Lattice as well as others) by late 1984. I think we can say it's been around for 37 years, +/- 3%.

And while Googling is fine, the way to check is to look at what's in <string.h>. It's not like it's a deep dark secret. It's right there on disk.

Use The Source, Luke.
 
  • Like
  • Haha
Likes Klystron, Jarvis323 and Mark44
  • #19
Jarvis323 said:
I think those functions are still `"optional", in that they are not required to be implemented.
All the ones that I mentioned (strcpy_s et al) have been present in Visual Studio for at least the past three editions - VS 2015, VS 2017, VS 2019 - and possibly earlier. yungman is using VS 2019.

Back in about 2004, the entire Windows division at MSFT (all 7500 people) were given a two-day training session aimed at increasing security in Windows. Part of the training involved awareness of hacking vulnerabilities coming from buffer overruns. The xxx_s functions in string.h were an effort to reduce or eliminate this particular vulnerability.
Vanadium 50 said:
And while Googling is fine, the way to check is to look at what's in <string.h>.
Or <cstring> which includes string.h. I couldn't agree more about doing quasi-random web searches. First place to look is in the header documentation.
 
  • Like
  • Informative
Likes Vanadium 50, Klystron and Jarvis323

What is a c-string?

A c-string is a sequence of characters that is terminated by a null character ('\0'). It is commonly used in the C programming language to represent text strings.

How do I declare a c-string?

To declare a c-string, you can use the char keyword followed by square brackets and the desired size of the string, for example: char string[10]. This will create an array of 10 characters, including the null character.

How can I search for a specific character in a c-string?

You can use the strchr() function from the library to search for a specific character in a c-string. This function returns a pointer to the first occurrence of the character in the string, or a null pointer if the character is not found.

Is it possible to search for more than one character in a c-string?

Yes, you can use the strncmp() function from the library to search for a specific sequence of characters in a c-string. This function takes three parameters: the c-string, the sequence to search for, and the number of characters to compare.

How can I search for just the first two characters in a c-string?

You can use the strncmp() function with the third parameter set to 2. This will compare the first two characters of the string with the specified sequence and return a pointer to the first occurrence of those characters, or a null pointer if they are not found.

Similar threads

  • Programming and Computer Science
Replies
5
Views
2K
  • Programming and Computer Science
3
Replies
89
Views
4K
  • Programming and Computer Science
Replies
3
Views
1K
  • Programming and Computer Science
Replies
1
Views
3K
  • Programming and Computer Science
Replies
5
Views
7K
  • Programming and Computer Science
3
Replies
75
Views
4K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
2K
  • Programming and Computer Science
Replies
7
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
24
Views
3K
  • Engineering and Comp Sci Homework Help
Replies
21
Views
3K
Back
Top