OJ 系列之字符串分割

問題描述

連續輸入字符串(輸出次數爲N,字符串長度小於100),請按長度爲8拆分每個字符串後輸出到新的字符串數組,

長度不是8整數倍的字符串請在後面補數字0,空字符串不處理。

例如:

輸入:abc

      12345789

輸出:abc00000

      12345678

      90000000

接口函數設計如下:

/*****************************************************************************
功能:存儲輸入的字符創

輸入:字符串

輸出:無
    
返回:0表示成功,其它返回-1
******************************************************************************/

int  AddString(char *strValue);
/****************************************************************************
功能:獲取補位後的二維數組的長度

輸入:無

輸出:無
    
返回:二維數組長度
*****************************************************************************/

int  GetLength();


/*****************************************************************************
功能:將補位後的二維數組,與輸入的二維數組做比較

輸入:strInput:輸入二維數組,iLen:輸入的二維數組的長度

輸出:無
    
返回:若相等,返回0;不相等,返回-1.其它:-1;
******************************************************************************/

int  ArrCmp(char strInput[][9],int iLen);


代碼實現

int strOutPut[1024][9];
int index = 0;
/*****************************************************************
功能:存儲輸入的字符串

輸入:字符串

輸出:無
     
返回:0表示成功,其它返回-1
****************************************************************/
int AddString(char *strValue)
{
	if(!strValue)
		return -1;

	int i=0,j=0;
	
	int strValueLen = strlen(strValue);
	if(strValueLen==0) 
		return -1;

	int multiple = strValueLen/8; /*得到8的倍數關係*/

/*不足8的情況*/
	if(0 == multiple) {
		for(i = 0;i < strValueLen;i++) {
			strOutPut[index][i] = strValue[i];
		}
		for(i = strValueLen;i < 8;i++) {
			strOutPut[index][i] = '0';
		}
		strOutPut[index][8] = '\0';
		index ++;
		
		return 0;
	}
/*截斷情況,剛好爲8的倍數*/
	for(i = 0;i<multiple;i++) {
		for(j=0;j<8;j++) {
			strOutPut[index][j] = strValue[i*j+j];
		}
		strOutPut[index][8] = '\0';
		index ++;
	}
/*截斷情況,最後一組超出8的倍數*/
	j = 0;
	for(i =multiple*8;i<strValueLen;i++) {
		strOutPut[index][j] = strValue[i];
		j ++;
	}
	for(i =strValueLen;i<(multiple+1)*8;i++) {
		strOutPut[index][j] = '0';
		j ++;
	}
	strOutPut[index][8] = '\0';
	
	index ++;
		
	return 0;
}

/****************************************************************
功能:獲取補位後的二維數組的長度

輸入:無

輸出:無
     
返回:二維數組長度
******************************************************************/
int GetLength()
{
	int len = index;
	
	return len;
}

/*****************************************************************************
功能:將補位後的二維數組,與輸入的二維數組做比較

輸入:strInput:輸入二維數組,iLen:輸入的二維數組的長度

輸出:無
     
返回:若相等,返回0;不相等,返回-1.其它:-1;
******************************************************************************/
int ArrCmp(char strInput[][9],int iLen)
{
	if(!strInput||iLen<=0)
		return -1;
	
	if(index!=iLen)
		return -1;
	
	int i = 0,j=0;
	for(i=0;i<iLen;i++) {
		for(j=0;j<8;j++) {
			if(strOutPut[i][j]!=strInput[i][j]) {
				index = 0; /*TO DO:沒有找到更好的辦法應對多個測試案例情況,只好在返回的時候清零*/
				return -1;
			}
		}
	}

	index = 0;

	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章