有关字符串的练习

1. 取两个字符串的最大公共子串
#include <iostream>
#include <string>

using namespace std;

int main()
{
	int n = 0;
	string a, b, t;
	
	cin >> a >>b;
	for (int i=0; i<a.size(); i++)
	{
		for (int j=a.size(); j>i&&j-i>n; --j)
		{
			string temp = a.substr(i, j-i);
			if (b.find(temp) != string::npos)
			{
				n = j-i;
				t = temp;
			}
		}
	}

	cout << t <<endl;

	return 0;
}
2. 求出一个串的最长重复子串
# include <stdio.h>
# define maximum 30

void StrInitiate(char *h)
{
	gets(h);
}

//串的长度
int StrLength(char *h)
{
	int count = 0;
	while (h[count] > 0)
	{
		count++;
	}

	return count;
}

//求出串的最长重复子串
void MaxSubStr(char *h, char *t)
{
	int lenmax = 0, len, index = 0;
	int i = 0, j, k;

	while (i < StrLength(h))
	{
		j = i+1;
		while (j < StrLength(h))
		{
			if (h[i] == h[j])
			{
				len = 1;
				for (k=1; h[i+k] == h[j+k]; k++)
					len++;
				if (len > lenmax)
				{
					index = i;
					lenmax = len;
				}
				j += len;
			}
			else
				j++;
		}
		i++;
	}

	for (i=0; i<lenmax; i++)
		t[i] = h[index+i];
}

//串的显示
void DisplayStr(char *h)
{
	for (int i=0; i<StrLength(h); i++)
		printf("%c", h[i]);
	printf("\n");
}

int main()
{
	char str[maximum];
	printf("输入串为:");
	StrInitiate(str);
	printf("\n");
	char t[maximum];

	MaxSubStr(str, t);
	printf("最大重复子串为:\n");
	DisplayStr(t);
	printf("\n");

	return 0;
}
3. 显示多位数数值将最多五位数的数值转换成字符的形式,在显示出来。在常用的word和txt文本中,
数字都是以字符形式存储的,因此本实验有实际的价值。 
/*************************************************************************
	功能:显示多位数数值
将最多五位数的数值转换成字符的形式,在显示出来。在常用的word和txt文本中,
数字都是以字符形式存储的,因此本实验有实际的价值。
	
	  思路:对于计算结果,从高位数开始,依次存入到祖父数组中,之后以字符
的形式显示出来。因此计算每个位数上的数值是关键步骤。例如,2538 = 2*1000 + 
5*100 + 3*10 + 8。
*************************************************************************/
# include <stdio.h>
# include <math.h>
# include <string.h>
# include <stdlib.h>

void main()
{
	char i[15], j[15];
	char r[15];

	for (int z=0; z<15; z++)
	{
		r[z] = NULL;
	}

	gets(i);
	gets(j);

	int oper1, oper2;
	int result;

	oper1 = atoi(i);
	oper2 = atoi(j);

	printf("两个操作数:%d and %d\n", oper1, oper2);
	printf("两数相乘: %d * %d = ", oper1, oper2);

	//以下程序的母的是将乘积以字符的形式打印至DOS中
	result = oper1 * oper2;
	int div = 10;
	while (result/div >= 10)
		div = div * 10;

	int count = 0;
	int t;
	while (div != 0)
	{
		t = result / div;
		r[count] = t + 48;
		result = result - div * t;
		div = div /10;
		count++;
	}

	puts(r);
}

posted @ 2017-09-04 11:19  actually96  阅读(156)  评论(0编辑  收藏  举报