WordReverse

来源:互联网 发布:西安交通大学网络 编辑:程序博客网 时间:2024/04/30 10:58

#include <stdlib.h>
#include "oj.h"
#include "stdio.h"
#include "string.h"

typedef struct node
{
 char * word;
 struct node * next;
}LinkNode;

/*
功能:
     对字符串中的所有单词进行倒排。
输入:
    char* pInput:给定的单词串
输出
    char* pOutput:倒排后的单词串
返回:
    int:成功0,失败-1
     */
int isString(char str)
{
 if (NULL == str)
  return -1;
 if ((str > 'a' && str < 'z')
  || (str > 'A' && str < 'Z')
  )
  return 1;
 else
  return 0;
}

char* clearEvpara(char* input)
{
 char * inpt;
 int count = 0;
 int i = 0;
 inpt = input;
 while(inpt[i] != '\0') {
  if (inpt[i] == '-')
   count++;
  else
   count = 0;
  if (count > 1)
   inpt[i] = ' ';
  i++;
 }
 return inpt;
}

int Converse(char* pInput, char* pOutput)
{
 char *pstr ;
 char *pword;
 int i = 0;
 int j = 0;
 int k = 0;
  int m = 0;
  int n = 0;
 int count =0;
 LinkNode *head,*plink;
 pstr = pInput;

 if (NULL == pstr)
  return -1;

 head = (LinkNode *)malloc(sizeof(LinkNode));
 if (NULL == head)
  return -1;
 head->word = (char *)malloc(sizeof(char) * 21);
 if (NULL == head->word)
  return -1;
 memset(head->word, NULL, sizeof(char) * 21);
 head->next = NULL;
m = (int)strlen(pstr) +1;
 //pstr =  clearEvpara(pInput);
 while(m--) {
  if (count < 2) {
   plink = (LinkNode *)malloc(sizeof(LinkNode));
   if (NULL == plink)
    return -1;
   plink->word = (char *)malloc(sizeof(char) * 21);
   if (NULL == plink->word)
    return -1;
   memset(plink->word, NULL, sizeof(char) * 21);
  }

  if (isString(pstr[n])) {
   plink->word[i++] = pstr[n];
   count++;
   if (isString(pstr[n++])){
    count++;
    continue;
   }
  } else {
   i = 0;
   count = 0;
  }

  plink->next = head;
  head = plink;

  n++;
 }

 pword = (char *)malloc(sizeof(strlen(pInput) + 1));
 if (NULL == pword)
  return -1;
 memset(pword, NULL, sizeof(strlen(pInput) + 1));

 while (head->next) {
  if (strlen(head->word) > 0) {
   k = 0;
   while(head->word[k] != '\0') {
    pword[j++] = head->word[k++];
   }
   pword[j++] = ' ';
   head = head->next;
  }
 }

 pOutput = pword;

 return 0;
}

 

 

char *pInput = "I am a - student";
  char *pResult = "student a am I";
    char szResult[100] = {0};
 CPPUNIT_ASSERT(0 == Converse(pInput, szResult));
 CPPUNIT_ASSERT(0 == strcmp(pResult, szResult));

0 0
原创粉丝点击