读书人

逆序打映字符串解决办法

发布时间: 2012-04-09 13:41:24 作者: rapoo

逆序打映字符串
如题:

[解决办法]
#include <stdio.h>
#include <iostream>

using namespace std;

int main() {
char str[100];

cout < < "Input a string: " < < endl;
cin.getline(str, 99);

char* p = str + strlen(str);
char* temp = NULL;
while (p != (str - 1)) {
if (*p == ' ' || p == str) {
temp = p+1;
if (p == str) temp--;
while (*temp != ' ' && *temp != '\0 ') {
cout < < *temp++;
}
cout < < ' ';
}

p--;
}

return 0;
}

[解决办法]
//###########################################################
//以下是源代码:
//###########################################################

//###################################
//MyString.h
//###################################
#ifndef _MYSTRING_H
#define _MYSTRING_H
#include <stdio.h>

class MyString_Item
{
public:
MyString_Item(char *buf,int len);
~MyString_Item();
char *m_buf;
int len;
void print();
MyString_Item *prev;
};

class MyString
{
public:
MyString(char *buf);
~MyString();
void print();
private:
MyString_Item *str;
};

#endif

//###################################
//MyString.cpp
//###################################
#include "MyString.h "

void memcpy(char *dst,char *src,int len)
{
int i;
if((dst==NULL)||(src==NULL)||(len <=0))
return;
for(i=0;i <len;i++)
dst[i] = src[i];
}

MyString_Item::MyString_Item(char *buf, int len)
{
m_buf = new char[len+1];
memcpy(m_buf,buf,len);
m_buf[len]=0;
}

MyString_Item::~MyString_Item()
{
delete m_buf;
}

void MyString_Item::print()
{
if(m_buf != NULL)
printf(m_buf);
}

MyString::MyString(char *buf)
{
int l;
char *p1;
char *p2;
MyString_Item *tmpitem;
str = NULL;
p1 = p2 = buf;
while(*p2!=0)
{
while((*p2!=32)&&(*p2!=0))
p2++;
tmpitem = new MyString_Item(p1,p2-p1);
p2++;
p1 = p2;
tmpitem-> prev = str;
str = tmpitem;
tmpitem = NULL;
}
}

MyString::~MyString()
{
MyString_Item *tmpitem;
tmpitem = str;
while(tmpitem!=NULL)
{
str = tmpitem-> prev;
delete tmpitem;
tmpitem = str;
}
}

void MyString::print()
{
MyString_Item *tmpitem;
tmpitem = str;
while(tmpitem!=NULL)
{
tmpitem-> print();
printf( " ");
tmpitem = tmpitem-> prev;
}
}

//###################################
//main.cpp
//###################################
#include "MyString.h "

void main()
{
MyString *str;
char istr[] = "Hello world ! I am a programer !\0 ";
str = new MyString(istr);
printf( "%s\n ",istr);
str-> print();
scanf( "%s ",istr);
}


//###################################################
//以下是命令行(运行结果)


//###################################################
Hello world ! I am a programer !
! programer a am I ! world Hello

读书人网 >C++

热点推荐