试题一:输入i love china 输出:china love i要求:除了定义一个数组用以存放字符串外,不得再使用其他的数组
方法一:(有一点bug)
#include<stdio.h>
#include<string.h>
//交换函数
char *exchange(char *ph,char *pe)
{
while(ph<pe)
{
*ph^= *pe;
*pe^=*ph;
*ph++^=*pe--;
}
}
//测定字符串长度函数
int fun(char *ph)
{
int i=1;
while(*ph!='\0')
{
if(*ph==' ')
i++;
ph++;
}
return i;
}
int main()
{
char * ph,*pe,a[20];
int i,n,k,count;
char *p1,*p2;
gets(a);
n=strlen(a);
ph=a;pe=a+n-1;
count=fun(ph);
exchange(ph,pe);
//对各个子串在进行交换
for(i = 0;i < count;i++)
{
k=0;
while(*ph!=' '&&*ph!='\0')
{
k++;
ph++;
}
p1=ph-k;
p2=ph-1;
exchange(p1,p2);
ph++;
}
puts(a);
return 0;
}
方法二:
#include <stdio.h>
#include <string.h>
#define N 30
unsigned int swap(char *head,char *tail);
unsigned int getdata(char * dest);
int main()
{
int count = 0;
char str[N + 1] = {0};
char *head = str,
*tail = str;
swap(str,str + getdata(str) - 1);//先整体交换
//从开始一个一个子串的进行交换
while(*tail != '\0' && *head != '\0')
{
while(*head == ' ' && *head != '\0')
head ++;
tail = head;
while(*tail != ' ' && *tail != '\0')
tail ++;
count = swap(head,tail - 1);
head = tail;
}
printf("count = %d\n",count);
puts(str);
return 0;
}
//输入字符串函数
unsigned int getdata(char * dest)
{
char ch;
int count = 0;
char *old = dest;
if(dest == NULL)
return 0;
while('\n' != (ch = getchar()) && count < N )
*dest ++ = ch,count ++;
*dest = '\0';
return dest - old;
}
//交换函数
unsigned int swap(char * head,char *tail)
{
static int i = 0;
if(head == NULL || tail == NULL)
return 0;
while(head < tail)
{
*head ^= *tail;
*tail ^= *head;
*head ++ ^= * tail -- ;
}
return ++ i;
}
试题二:输入:一个字符串由数字子串和字母子串组成(不区分大小写)输出:其最大子串的长度
#include<stdio.h>
#define N 40
int sub_srting(char *ph)
{
int m,k=0,i,b[N]={0};
char *pe=ph;
while(*pe!='\0')
{
while((*pe>='0'&&*pe<='9')&&*pe!='\0')
pe++;
b[k++]=pe-ph;
ph=pe;
while((*pe>='a'&&*pe<='z'||*pe>='A'&&*pe<='Z')&&*pe!='\0')
pe++;
b[k++]=pe-ph;
ph=pe;
}
for(i=0;i<=k-2;i++)
if(b[i]>b[i+1])
{
b[i]^=b[i+1];
b[i+1]^=b[i];
b[i]^=b[i+1];
}
return b[i];
}
int main()
{
char a[N];
gets(a);
printf("the lengest substring is %d\n",sub_srting(a));
return 0;
}