Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
104 views
in Technique[技术] by (71.8m points)

c++ - strcmp or string::compare?

I want to compare two strings. Is it possible with strcmp? (I tried and it does not seem to work). Is string::compare a solution?

Other than this, is there a way to compare a string to a char?


Thanks for the early comments. I was coding in C++ and yes it was std::string like some of you mentioned. I didn't post the code because I wanted to learn the general knowledge and it is a pretty long code, so it was irrelevant for the question.

I think I learned the difference between C++ and C, thanks for pointing that out. And I will try to use overloaded operators now. And by the way string::compare worked too.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For C++, use std::string and compare using string::compare.

For C use strcmp. If your (i meant your programs) strings (for some weird reason) aren't nul terminated, use strncmp instead.

But why would someone not use something as simple as == for std::string ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...