codepad
[
create a new paste
]
login
|
about
Language:
C
C++
D
Haskell
Lua
OCaml
PHP
Perl
Plain Text
Python
Ruby
Scheme
Tcl
// SMS Problem (Multiple Key Press) - #-Break, 1 - NULL, 2 - ABC2, ...etc // //#define DEBUG_PRINT #include <stdio.h> char* MultiKeyStrokeParser(char *pKeys); void PrintParsedText(char *pKeys); int main(int argc, char *args[]) { printf("\n"); PrintParsedText("22"); // B PrintParsedText("23"); // AD PrintParsedText("223"); // BD PrintParsedText("22#2"); // BA (# breaks the cycle) PrintParsedText("3#33"); // DE PrintParsedText("2222"); // 2 PrintParsedText("2222#2"); // 2A PrintParsedText("22222"); // A (cycle must wrap around) PrintParsedText("222222"); // B PrintParsedText("#33#44#"); // EH PrintParsedText("#44#444"); // HI PrintParsedText("#4*222#"); // G C PrintParsedText("33*222*4"); // E C G } void PrintParsedText(char *pKeys) { #ifdef DEBUG_PRINT printf("\n"); #endif char *pText = MultiKeyStrokeParser(pKeys); printf("Input Keys = %s, Output Text = %s\n", pKeys, pText ? pText : "NULL"); if (NULL != pText) { free(pText); pText = NULL; } } char* MultiKeyStrokeParser(char *pKeys) { static char *pMappings[] = { "1", "2ABC", "3DEF", "4GHI", "5JKL", "6MNO", "7PQRS", "8TUV", "9WXYZ" }; int errorCode; int i, nText, nCount, nCh, j; int fConvert; int nKeys = strlen(pKeys); char *pText = NULL; char *pMap; #ifdef DEBUG_PRINT printf("DEBUG : Input Keys = %s, Length = %d\n", pKeys, nKeys); #endif pText = (char *) malloc((nKeys + 1) * sizeof(char)); if (NULL == pText) { printf("ERROR : Insufficient memory!"); errorCode = -1; goto Exit; } nText = 0; fConvert = 0; for (i = 0, nCount = 0, j = 0; j < nKeys; ) { // Make sure only numbers, break (#), and space (*) are pressed // if ((pKeys[j] < '0' || pKeys[j] > '9') && (pKeys[j] != '#') && (pKeys[j] != '*') && (pKeys[j] != '\0')) { printf("ERROR : Invalid Input Character!\n"); errorCode = -2; goto Exit; } if (pKeys[i] == '#') { i++; nCount = 0; fConvert = 0; j = i; } else if (pKeys[i] == '*') { i++; nCount = 0; fConvert = 0; j = i; pText[nText++] = ' '; } else if (pKeys[i] == pKeys[j]) { nCount++; j++; fConvert = 0; } else { fConvert = 1; } if (j == nKeys) fConvert = 1; if (fConvert) { nCh = (int) (pKeys[i] - '0'); if (nCh < 0 || nCh > 9) break; pMap = pMappings[nCh-1]; #ifdef DEBUG_PRINT printf("DEBUG : Char = '%c' / %d, Count = %d, Map = %s \n", pKeys[i], nCh, nCount, pMap); #endif pText[nText++] = pMap[nCount % strlen(pMap)]; i += nCount; j = i; fConvert = 0; nCount = 0; } } pText[nText++] = '\0'; // NULL Terminate errorCode = 0; Exit: if (errorCode < 0) { free(pText); pText = NULL; } return pText; }
Private
[
?
]
Run code
Submit