利用string类重载运算符!=比较string类字符串

// ex5-11.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include <string>
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
	string word="?ate";
	for (char ch='a';word!="mate";++ch)
	{
		cout<<word<<endl;
		word[0]=ch;//第一次循环结束并不显示当前新词,但是会在下次循环开始时比较
	}
	cout<<"now the word is:"<<word<<endl;
	system("pause");
	return 0;
}


使用string类更简单直观


没有指定循环次数,所以不是计数循环

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的字符串 string 的定义,其中包含了重载运算符“==”、“<”和“>”: ```cpp class string { public: string() : data(nullptr), length(0) {} // 默认构造函数 string(const char* str) : data(nullptr), length(0) { // 构造函数,初始化字符串 if (str != nullptr) { length = strlen(str); data = new char[length + 1]; strcpy(data, str); } } string(const string& other) : data(nullptr), length(other.length) { // 拷贝构造函数 if (other.data != nullptr) { data = new char[length + 1]; strcpy(data, other.data); } } ~string() { // 析构函数 if (data != nullptr) { delete[] data; data = nullptr; length = 0; } } string& operator=(const char* str) { // 重载运算符“=” if (data != nullptr) { delete[] data; data = nullptr; length = 0; } if (str != nullptr) { length = strlen(str); data = new char[length + 1]; strcpy(data, str); } return *this; } string& operator=(const string& other) { // 重载运算符“=” if (this == &other) { return *this; } if (data != nullptr) { delete[] data; data = nullptr; length = 0; } if (other.data != nullptr) { length = other.length; data = new char[length + 1]; strcpy(data, other.data); } return *this; } bool operator==(const string& other) const { // 重载运算符“==” if (length != other.length) { return false; } return strcmp(data, other.data) == 0; } bool operator<(const string& other) const { // 重载运算符“<” return strcmp(data, other.data) < 0; } bool operator>(const string& other) const { // 重载运算符“>” return strcmp(data, other.data) > 0; } private: char* data; // 存放字符串的指针 size_t length; // 字符串的长度 }; ``` 在上面的代码中,我们使用了动态内存分配来存放字符串。在构造函数和拷贝构造函数中,我们使用了 strcpy 函数来将字符串拷贝到内存中。在重载运算符“=”中,我们先将原来的字符串释放掉,再根据传入的参数重新分配内存和拷贝字符串。在重载运算符“==”、“<”和“>”中,我们使用了 strcmp 函数来比较两个字符串的大小关系。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值