Thursday, July 21, 2011

反轉字串的C程式

// a2.cpp : 定義主控台應用程式的進入點。
//
#include "stdafx.h"
反轉字串的C程式

輸入任意字串,輸出為這個字串的反轉


// a2.cpp : 定義主控台應用程式的進入點。
//
#include "stdafx.h"
#include <iostream>
#include <cstdlib>

using namespace std;
char* inv(char *, int);

int main(int argc, _TCHAR* argv[])
{
 int len = 0;
 char str[30];
 char *p;
 printf("請輸入一字串:");
 gets_s(str);
 len = strlen(str);
 p = inv(str,len);
 printf("反轉的字串為:");

 for (int i = 0; i < len ; i++)
  printf("%c",*(p+i));
 system("pause");
 return 0;
}

char* inv(char *s, int len)
{

 char *s2 = new char[len];
 for (int i = 0; i < len ; i++)
  *(s2 + i) = *(s + len - 1 -i);

 return s2;
}

No comments:

Post a Comment