《資料結構與演算法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 [email protected]$789# 1 Hello:World! 10 Hello;World! -1Sample 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();
}
}