《數據結構與算法A》實驗3:字符串的簡單加密

題目:

Description

假設字符串中只可能包含“大小寫英文字母”、“阿拉伯數字”和10種其他符號(包括:'!'、'#'、'@'、'+','-','*','?','$',':',';')。請編寫代碼,當讀入一個字符串(長度不超過50個字符)之後,使用順序表存儲字符串,並通過以下方式實現加密:首先,去掉字符串中的阿拉伯數字和其他符號;其次,將剩餘的英文字母轉換成ASCII碼錶中其後的第n(1≤n≤10)個字符;最後,輸出加密後的字符串(可能爲空字符串)。

順序表的參考代碼如下:

const  int  MaxListSize=10; //根據問題修改該值

class SeqCharList{

    char data[MaxListSize]; //存儲字符串

    int size;            //元素個數

  public:

    SeqCharList( );  //構造函數

    void Clear( );        //清空表

    bool IsEmpty( );     //判斷如果爲空表,返回true,否則返回false

    char Get(int k);    //返回第k個字符

    int Locate(char e);      //返回第一個與元素e匹配的元素位序

    char Delete(int i);        //刪除第i個元素,並返回所刪除元素值

    void Print( );    //輸出字符串

    void Encryption( );    //字符串加密

}; //SeqCharList

Input

本實驗包含多組測試數據,每組數據包含兩行:第一行輸入n(1≤n≤10),表示使用ASCII碼錶中其後的第n個字符進行加密;第二行輸入要加密的字符串。當輸入n=-1時,做爲測試結束標誌。

Output

輸出加密後的字符串,並且每個加密字符串佔一行。注意:當加密之後爲空字符串時,則只輸出換行。

Sample Input

8
Hello?World!
5
123@456$789#
1
Hello:World!
10
Hello;World!
-1

Sample Output

Pmttw_wztl

IfmmpXpsme
Rovvyay|vn

感想: 

    話說這道題完全不需要實現這個類吧,裏面的函數一點都沒用上。。。。。。

題解:

#include<iostream>
#include<cstring>
#include<string>

using namespace std;

const  int  MaxListSize = 50; //根據問題修改該值
class SeqCharList {
	char data[MaxListSize]; //存儲字符串
	int size;            //元素個數
public:
	SeqCharList();  //構造函數
	SeqCharList(string str);
	void Clear();        //清空表
	bool IsEmpty();     //判斷如果爲空表,返回true,否則返回false
	char Get(int k);    //返回第k個字符
	int Locate(char e);      //返回第一個與元素e匹配的元素位序
	char Delete(int i);        //刪除第i個元素,並返回所刪除元素值
	void Print();    //輸出字符串
	void Encryption(int n);    //字符串加密
}; //SeqCharList

SeqCharList::SeqCharList() {
	size = 0;
}

SeqCharList::SeqCharList(string str) {
	size = str.length();
	for (int i = 0; i < size; i++)
		data[i] = str[i];
}

void SeqCharList::Clear() {
	size = 0;
}

bool SeqCharList::IsEmpty() {
	return size == 0;
}

char SeqCharList::Get(int k) {
	return data[k];
}

int SeqCharList::Locate(char e) {
	for (int i = 0; i < size; i++) {
		if (data[i] == e)
			return i;
	}
}

char SeqCharList::Delete(int i) {
	char r = data[i];
	for (int j = i + 1; j < size; j++)
		data[j - 1] = data[j];
	size--;
	return r;
}

void SeqCharList::Print() {
	if (size == 0)
		cout << endl;
	else
	{
		for (int i = 0; i < size; i++)
		{
			cout << data[i];
		}
		cout << endl;
	}
}

void SeqCharList::Encryption(int n) {
	int size2 = 0;
	char data2[MaxListSize];
	for (int i = 0; i < size; i++)
	{
		if ((data[i] >= 'a'&&data[i] <= 'z') || (data[i] >= 'A'&&data[i] <= 'Z'))
		{
			data2[size2] = data[i] + n;
			size2++;
		}
	}
	size = size2;
	for (int i = 0; i < size; i++)
		data[i] = data2[i];
}


int main() {
	int n;
	string str;
	while (1) {
		cin >> n;
		if (n == -1)
			break;
		cin >> str;
		SeqCharList seq(str);
		seq.Encryption(n);
		seq.Print();
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章