查找子串在母串中的位置、编写一个函数实现字符串拼接【数据结构实验报告算法详解】

一、查找子串在母串中的位置

#include<iostream>
using namespace std;

int SearchIndex(char* str1, char* str2)  //返回子串起始位在主串中的下标
{
	int i, j;
	for(i=0; i<sizeof(str1); i++)
	{
		if(str1[i]==str2[0])  //遍历到的字符与str2的首字符对应上了 
			for(j=1; j<sizeof(str2); j++)  //就开始扫描str2剩下的字符是否都能与str1中的某段对应上
			{
				if(str1[i+j]==str2[j])
					if(str2[j]!='\0')
						return(i);  //若str2被遍历完,说明都对应上了,返回此时主串的下标 
				else
					break;  //只要有一个不对应,就跳出遍历str2 
			}				
	}
}

int main()
{
	char str1[10]= "abcdefg";  //主串 
	char str2[10]= "gh";  //子串 
	int res= SearchIndex(str1, str2);  //返回的下标,或者出错码 
	if(res==8)
		cout << str2 << "子串不存在于" << str1 << "主串中!"; 
	else
		cout << str2 << "子串在" << str1 << "主串的【" << res << "】位置上!"; 	
}

11
1-2
1-3

二、一个实现字符串拼接的函数

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

char* Strcat(char* str1, const char* str2) {
	int n = strlen(str1);
	int i = 0;
	//字符串str1的地址和str2的地址同时后移,依次进行赋值,直到str2为空退出 
	while(str1++[i + n] = str2++[i])  ;
	return str1;
}

int main()
{
	char str1[10] = "abcd";
	char str2[10] = "efghi123";
	Strcat(str1, str2);
	cout << "连接后的字符串为:" << str1; 
}

2-1

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鸿蒙Next

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值