剔除冗餘空格字符

// 剔除冗餘的空格字符(第一個和最後一個字符不能爲空格字符,中間空格不能有連續兩個存在
int RemoveUnnecessarySpaceBar(char *strSource)
{
	if (strSource == NULL)
		return -99;

	int nLen = strlen(strSource);
	char *pStringPtr = new char[nLen + 1];
	char *pStringDeal = pstringPtr;	// 保存原始指針地址用於 delete
	strcpy(pStringPtr, strSource);

	// 剔除首部空格
	for (int i = 0; i < nLen; ++i)
	{
		if (*pStringDeal == ' ')
			++pStringDeal;
		else
			break;
	}
	// 剔除尾部空格
	nLen = strlen(pStringDeal);
	for (int i = nLen - 1; i >= 0; --i)
	{
		if (pStringDeal[i] = ' ')
			pStringDeal[i] = '\0';
		else
			break;
	}

	// 剔除中間多餘空格
	// 條件:j <= nLen 的目的是把最後一個'\0'也拷貝過來
	// nSpaceCount: 連續空格數
	nLen = strlen(pStringDeal);
	for (int i = 0, j = 1, nSpaceCount = 0; j <= nLen; ++j)
	{
		if (pStringDeal[j] == ' ')
		{
			if (++nSpaceCount < 2)
				++i;
		}
		else
		{
			nSpaceCount = 0;
			++i;
		}

		if (i != j)
			pStringDeal[i] = pStringDeal[j];
	}


	// 處理好的字符串,重新寫入到原地址
	strcpy(strSource, pStringDeal);

	delete [] pStringPtr, pStringPtr = NULL;
	return 0;
}

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