C/C++数据结构:串的五个常用操作

cpp 复制代码
/**
*
* Althor: Hacker Hao
* Create: 2023.10.14
*
*/
#include <bits/stdc++.h>
using namespace std;
#define MAXSIZE 200
#define ERROR -1
#define OK 1
typedef struct
{
	char data[MAXSIZE];
	int length;
}SqString;
//实现串赋值、串比较、求串长、串联接以及求子串这5种基本操作。

void Assign(SqString &s, char str[])
{
	int i = 0;
	for (i = 0; str[i] != '\0'; i++)
		s.data[i] = str[i];
	s.length = i;
}

void Compare(SqString *s1, SqString *s2)
{
	int i = 0;
	for (i = 0; s1->data[i] != '\0' && s2->data[i] != '\0'; i++)
	{
		if (s1->data[i] > s2->data[i])
		{
			cout << "前者大" << endl;
			return;
		}

		if (s1->data[i] < s2->data[i])
		{
			cout << "后者大" << endl;
			return;
		}
	}
	cout << "一样大" << endl;
	return;
}

int Length(SqString* s)
{
	return s->length;
}

void Concat(SqString* s1, SqString* s2, SqString* s)
{
	int t = 0;
	if (s1->length + s2->length <= MAXSIZE)
	{
		for (int i = 0; i < s1->length; i++)
		{
			s->data[i] = s1->data[i];
		}
		for (int i = 0, j = s1->length; j < s1->length + s2->length; i++, j++)
		{
			s->data[j] = s2->data[i];
		}
		s->length = s1->length + s2->length;
		t = s->length;
	}
	else
	{
		for (int i = 0; i < s1->length; i++)
		{
			s->data[i] = s1->data[i];
		}
		for (int i = 0, j = s1->length; i< MAXSIZE - s1->length; i++, j++)
		{
			s->data[j] = s2->data[i];
		}
		t = MAXSIZE;
	}
	cout << "新的链接好的串为:" << endl;
	for (int i = 0; i < t; i++)
	{
		cout << s->data[i];
	}
	cout << endl;
}
int SubString(SqString &Sub, SqString s, int pos, int len)
{
	if (pos < 1 || pos > s.length || len < 0 || len > s.length - pos + 1)
		return ERROR;
	for (int i = 0; i < len; i++,pos++)
	{
		Sub.data[i] = s.data[pos];
	}
	Sub.length = len;

	for (int i = 0; i < len; i++)
	{
		cout << Sub.data[i];
	}
	cout << endl;

	return OK;
}

int main()
{
	cin.tie(0), cout.tie(0);
	SqString s1, s2, s3, Sub;

	char str1[200] = "hello";
	char str2[200] = "nihao";
	Assign(s1, str1);
	Assign(s2, str2);

	Compare(&s1, &s2);

	cout << "s1的长度为:" << Length(&s1) << endl;
	cout << "s2的长度为:" << Length(&s2) << endl;

	Concat(&s1, &s2, &s3);

	cout << "输出的字串为:" << endl;
	SubString(Sub,s3, 3, 4);
	return 0;
}
相关推荐
无限进步_19 分钟前
深入理解 C/C++ 内存管理:从内存布局到动态分配
c语言·c++·windows·git·算法·github·visual studio
JANGHIGH29 分钟前
c++ 多线程(三)
开发语言·c++
长安er34 分钟前
LeetCode 34排序数组中查找元素的第一个和最后一个位置-二分查找
数据结构·算法·leetcode·二分查找·力扣
点云SLAM1 小时前
C++ 中traits 类模板(type traits / customization traits)设计技术深度详解
c++·算法·c++模板·c++高级应用·traits 类模板·c++17、20·c++元信息
liu****1 小时前
9.二叉树(一)
c语言·开发语言·数据结构·算法·链表
sin_hielo1 小时前
leetcode 3577
数据结构·算法·leetcode
铁手飞鹰2 小时前
[HAL库分析—GPIO]
c语言·stm32·单片机·嵌入式硬件
水饺编程2 小时前
第3章,[标签 Win32] :处理 WM_PRINT 消息
c语言·c++·windows·visual studio
虚假程序设计2 小时前
pythonnet 调用C接口
c语言·python
慕容青峰3 小时前
【LeetCode 1925. 统计平方和三元组的数目 题解】
c++·算法·leetcode