Implementation of string size comparison function

Source: Internet
Author: User
Tags comparison

Now C + + has supported direct comparisons between strings.

But the previous time encountered a pen question, let oneself implement the function to complete the comparison between two strings.

As we all know, the comparison process is very simple, is a character-by-letter comparison of the size of the ASCII code value. But it was a little bit of a hassle when it came true personally.

The code is as follows for Yimeimei reference

Exp2.cpp: Defines the entry point of the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int Scompare (string s1,string s2);
int main ()
{
	
	cout<< "enter S11" <<endl;
	string S11,s22;
	Getline (CIN,S11);
	cout<< "Enter S22" <<endl;
	Getline (CIN,S22);
	Switch (Scompare (S11,S22)) {case
	0:cout<< "S1>s2" <<endl;break;
	Case 1:	cout<< "S1<s2" <<endl;break;
	Case 2:cout<< "S1=s2" <<endl;
	}
	return 0;
}
int Scompare (const string S1,const string s2) {
int i=0;
while (s1[i]!= ' &&s2[i]!= ') {
	if (S1[i]>s2[i])
		return 0;
	 if (S1[i]<s2[i])
		return 1;
	if (S1[i]==s2[i])
		i++;
}
if (s1[i]!= ')
	return 0;
if (s2[i]!= ')
	return 1;
if (s1[i]== ' &&s2[i]== ')
	return 2;
}


The biggest trouble with this process is that in the process of writing the Scompare function, the formal parameter is not defined as a const type, resulting in a always-crossed error.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.