1. 程式人生 > >C語言_輸出字串中最長的一個大小寫字母組合

C語言_輸出字串中最長的一個大小寫字母組合

首先讀一個字元,判斷該字元是否為字母:

如果該字元為字母,則存入字母緩衝區,如果該字母后面為結束符,則記錄該字母組合的長度、起始和結束下標。

如果該字元不是字母,但該字元的前一個字元是字母,則記錄該字母組合的長度、起始和結束下標。清空字母緩衝區。

如果該字元不是字母且其前一個字元也不是字母,則讀取下一個字元。

#include <stdio.h>
#define SIZE 50
struct stack{
	int charCount;
	int indexStart;
	int indexEnd;
};
int main(){
	int i,j,k,wordCount,num,max,ptr;
	char strBuffer[SIZE];
	struct stack wordStack[SIZE];
	char str[]="
[email protected]
&z??ABCD** BabyBaby ()"; printf("%s\n",str); for(i=0;i<SIZE;i++){ wordStack[i].charCount=0; wordStack[i].indexStart=0; wordStack[i].indexEnd=0; } i=0;j=0;wordCount=0; while(str[i]!='\0'){ if(str[i]>='A'&&str[i]<='Z'||str[i]>='a'&&str[i]<='z'){ strBuffer[j]=str[i]; i++;j++; if(str[i]=='\0'){ wordStack[wordCount].charCount=j; wordStack[wordCount].indexEnd=i-1; wordStack[wordCount].indexStart=i-j; wordCount++; } }else if(i>=1&&str[i-1]>='A'&&str[i-1]<='Z'||str[i-1]>='a'&&str[i-1]<='z'){ wordStack[wordCount].charCount=j; wordStack[wordCount].indexEnd=i-1; wordStack[wordCount].indexStart=i-j; wordCount++; for(k=0;k<SIZE;k++){ strBuffer[k]='\0'; } i++;j=0; }else{ i++; j=0; } } max=0;ptr=0; for(i=0;i<wordCount;i++){ num=wordStack[i].charCount; if(num>max){ max=num; ptr=i; } } i=wordStack[ptr].indexStart; j=wordStack[ptr].indexEnd; for(k=i;k<=j;k++){ printf("%c",str[k]); } return 0; }