编程珠玑【学习笔记】:习题 编程珠玑2nd 3.7 第五题

来源:互联网 发布:k均值聚类算法原理课件 编辑:程序博客网 时间:2024/06/05 11:46
//编程珠玑2nd   3.7  第5题   由于我的能力有限,可能会出现一些愚蠢的错误,若您能提出宝贵意见,我将不胜感激!//欢迎您与我联系!【我的邮箱】:lxw0109@gmail.com //题目:本问题将处理一小部分用连字符连接的英语单词方面的问题。下面的规则列表描述了一些以字母c结尾的单词的有效//连字符连接:et-ic al-is-tic s-tic p-tic -lyt-ic ot-ic an-tic n-tic c-tic at-ic h-nic n-ic m-ic l-lic b-lic //-clic l-ic h-ic f-ic d-ic -bic a-ic -mac i-ac  应用该规则时,必须按照上述次序进行;从而导致了"ethnic"(遵循//规则"h-nic")和"clinic"(不满足前一规则,但遵循"n-ic")。如果在某个函数中给定一个单词你必须返回后缀连字符连接//你该如何表示这样的规则呢?#include <iostream>#include <cstring>using namespace std;void swap(char * tem_word, int length){//将单词首尾反序int i, times = length / 2;char ch;for(i = 0; i < times; ++ i){ch = tem_word[i];tem_word[i] = tem_word[length - 1 - i];tem_word[length - 1 - i] = ch;}}bool func(char * word, char * dest, int length){//dest为欲求的word的后缀的反序bool flag = false;char arr[24][10] = {//最长的单词的长度是 9,但列数为10,原因main函数中最后一句话"ci-td" , "cit-si-al" , "cit-p" , "ci-tyl-" , "ci-to" , "cit-na" , "cit-n" , "cit-c" , "cit-ta" ,"ci-ta" , "cin-h" , "ci-n" , "ci-m" , "cil-l" , "cil-b" , "cilc-" , "ci-l" , "ci-h" , "ci-f" ,"ci-d" , "cib-" , "ci-a" , "cam-" , "ca-i"};char arr1[24][8] = {"citd" , "citsial" , "citp" , "cityl" , "cito" , "citna" , "citn" , "citc" , "citta" ,"cita" , "cinh" , "cin" , "ci-m" , "cill" , "cilb" , "cilc" , "cil" , "cih" , "cif" ,"cid" , "cib" , "cia" , "cam" , "cai"};char * temp_str = new char[length + 1];strcpy(temp_str, word);swap(temp_str, length);//单词完成反序//依次和后缀数组arr1中元素进行比较int i, len, j;for(i = 0; i < 24; ++ i){len = strlen(arr1[i]);if(len > length)continue;else{char * bk_str = new char[len + 1];for(j = 0; j < len; ++ j){bk_str[j] = temp_str[j];}bk_str[j] = '\0';//此语句必须有啊!if(strcmp(bk_str, arr1[i]) == 0){//dest = new char[len + 3];//此时一旦函数返回,则被调用的函数内申请的空间将被释放,并且不能被访问到!所以这样写是不对的!strcpy(dest, arr[i]);flag = true;break;}elsecontinue;}}delete temp_str;return flag;}int main(){char * word = new char[20];char * dest = new char[20];;cin >> word;if(func(word, dest, strlen(word))){//如果为真说明找到swap(dest,strlen(dest));cout << dest << endl;}else{cout << "Cannot find the bk_str ! " << endl;}delete word;delete dest;//char worda[10] = "123456789";//需要为'\0'留出一个位置,申请空间时 new char[strlen(...) + 1] ,以前遇到过return 0;}//result://clinic// n-ic// //ethnic// h-nic


原创粉丝点击