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;
}
相关推荐
剑锋所指,所向披靡!1 小时前
C++之类模版
java·jvm·c++
鱼跃鹰飞2 小时前
Leetcode347:前K个高频元素
数据结构·算法·leetcode·面试
C+-C资深大佬2 小时前
C++风格的命名转换
开发语言·c++
No0d1es2 小时前
2025年粤港澳青少年信息学创新大赛 C++小学组复赛真题
开发语言·c++
点云SLAM2 小时前
C++内存泄漏检测之手动记录法(Manual Memory Tracking)
开发语言·c++·策略模式·内存泄漏检测·c++实战·new / delete
好评1242 小时前
【C++】二叉搜索树(BST):从原理到实现
数据结构·c++·二叉树·二叉搜索树
zylyehuo2 小时前
error: no matching function for call to ‘ros::NodeHandle::param(const char [11], std::string&, const char [34])’
c++·ros1
程序猿炎义3 小时前
【Easy-VectorDB】Faiss数据结构与索引类型
数据结构·算法·faiss
星火开发设计3 小时前
C++ 函数定义与调用:程序模块化的第一步
java·开发语言·c++·学习·函数·知识
天赐学c语言3 小时前
1.20 - x的平方根 && vector的扩容机制以及删除元素是否会释放内存
c++·算法·leecode