算法练习1:Take every 2nd char from the string. Then the other chars 随笔

来源:互联网 发布:twitter是什么软件 编辑:程序博客网 时间:2024/04/29 07:59

题目和要求:


十分全的string函数:

http://www.jb51.net/article/41725.htm

可能用到的函数:

-------删除函数 :erase();

#include<string>using namespace std;...string s1="asdfgh", s2;s2=s1.erase(2,3); //删除s1中从第2个字符其的3个字符。则s2的内容为"ash"

--------赋值函数:assign();

str2.assign(str1);即用str1给str2赋值a.assign(b,i,n); // 把b[i..i+n-1]赋值给a
如果直接用“=”赋值将会两者指针指向同一个地方,使用strcpy是出现不知名错误。“no matching”,copy也不能用。

-------插入函数:insert();

//#include "stdafx.h"//If the vc++6.0, with this line.
#include <string>
#include <iostream>
using namespace std;//
int main(void){
    string a="1234567890",b="abcdefghijklmn";
    a.insert(3,b,5,4);
    cout << a << endl;
    return 0;
}

输出是123fghi4567890.

--------总结:有许多函数不清楚用法的时候先测试函数是否使用得和自己想象的一样效果,否则只会做无用功。



--------最终完成的代码:

std::string encrypt(std::string text, int n){     std::string tmp;     std::string tmp_1;       for(int i=0;i<n;i++)    {  tmp_1.assign(text);       tmp.erase(0,tmp.length());        for(int j=1;j<=text.length()/2;j++)          {       tmp+=tmp_1[j];       tmp_1.erase(j,1);           }      text=tmp+tmp_1;    }        return text;}std::string decrypt(std::string encryptedText, int n){std::string tmp_2;std::string tmp_3;int boundedNumber=encryptedText.length()/2;    for(int i=0;i<n;i++)    {tmp_2.assign(encryptedText,0,boundedNumber);tmp_3.assign(encryptedText,boundedNumber,encryptedText.length());      for(int j=0;j<boundedNumber;j++)      {        tmp_3.insert(2*j+1,tmp_2,j,1);         }      encryptedText=tmp_3;    }               return encryptedText;}


0 0
原创粉丝点击