天天看點

華為機試題: 字元串分割

描述: 

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

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

例如:

輸入:abc

      12345789

輸出:abc00000

      12345678

      90000000

接口函數設計如下:

int  AddString(char *strValue);

int  GetLength();

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

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

char sstr[15][9] = { 0 };
int size = 0;
/*****************************************************************
功能:存儲輸入的字元創

輸入:字元串

輸出:無
     
傳回:0表示成功,其它傳回-1
****************************************************************/
int  AddString(char *strValue)
{
	if (strValue == NULL || strlen(strValue) == 0 || strlen(strValue) > 100)
	{
		return -1;
	}

	int row = 0, i = 0;

	for (i = 0; strValue[i] != '\0'; i++)
	{
		sstr[size][row] = strValue[i];
		row++;
		if (row == 8)
		{
			sstr[size][row] = '\0';
			size++;
			row = 0;
		}
	}
	if (row != 0)
	{
		for (i = strlen(strValue) % 8; i < 8; i++)
		{
			sstr[size][i] = '0';
		}

		sstr[size][8] = '\0';
		size++;
	}
	
	
	return 0;
}

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

輸入:無

輸出:無
     
傳回:二維數組長度
******************************************************************/
int  GetLength()
{
	return size;
}

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

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

輸出:無
     
傳回:若相等,傳回0;不相等,傳回-1.其它:-1;
******************************************************************************/
int  ArrCmp(char strInput[][9],int iLen)
{
	if (strInput == NULL || iLen == 0)
	{
		return -1;
	}

	int i = 0, j = 0;
	for (i = 0; i < iLen; i++)
	{
		for (j = 0; j<9; j++)
		{
			if (strInput[i][j] != sstr[i][j])
				return -1;
		}
	}

	for (i = 0; i < 15; i++)//最後需要清零
	{
		for (j = 0; j<9; j++)
		{
			sstr[i][j] = '0';
		}
	}
		
	size = 0;
	return 0;
}
           

主函數測試用例:

#include <iostream>
#include "source\OJ.h"

using namespace std;


int main()
{
	AddString("434353f");
	AddString("ABCDEFG1234");
	AddString("1234567890");

	char strRst[][9] = { "434353f0", "ABCDEFG1", "23400000", "12345678", "90000000" };

	cout << GetLength() << endl;
	cout << ArrCmp(strRst, 5) << endl;



	system("PAUSE");
	return 0;
}
           

繼續閱讀