Little function
A.First Edition
This is the first edition of this simple function to delete first and last non-alphabetic char of a string.
1¡£ Basic idea:
2¡£ Program design:
3¡£ Major function£º
A.
4¡£ Further improvement£º
A. I write it for fun with a couple of hours and I am not interested in improving it.
#include <iostream>
using namespace std;
void removeMark(char* word);
void arrange(char* dictionary, const int arraySize, int wordSize);
//the testing data, make sure the total char including '\0' not exceeding the max length of
//word length; otherwise you will make two word as one long word,
char* str[5] = {"$firsts", "$secon&", "&fully&", "normal&", "w*"};
int main()
{
//this is a little test to show you the effect
char dictionary[40];// this is your big array with 5 word, each 8bytes
//I now fill in with 5 word with punches
for (int i =0; i<5; i++)
{
//use address of first char as a string to accept the words
strcpy(&dictionary[i*8], str[i]);
}
//show you the word before "arrange"
cout<<"\nNow is the word before arrange\n";
for (int j =0; j<5; j++)
{
char* ptr;
ptr = &dictionary[j*8];
cout<<ptr<<endl;
}
//arrange with 5words, each 8bytes arrange(dictionary, 5, 8);
//show you the effect after arrange
cout<<"\nNow I show you the effect after arrange\n";
for (j =0; j<5; j++)
{
char* ptr;
ptr = &dictionary[j*8];
cout<<ptr<<endl;
}
return 0; }
void removeMark(char* word)
{
char * ptrFirst, *ptrSecond;
char ch; ch = word[0]; //I have to store the first char as it will be changing after copy ptrFirst = word; ptrSecond = ptrFirst +1;
while (*ptrFirst!= '\0')
{
//you need to seperate two situation:
//this is the first char is not a alphabetic
if (!isalpha(ch))
{
//you copy each char from next to previous
*ptrFirst = *ptrSecond;
//and move to next char ptrFirst = ptrSecond; ptrSecond = ptrFirst + 1;
//until you find out the last char is also not alphabetic
//unless you notice the ptrSecond is '\0'
if (*ptrSecond=='\0'&&(!isalpha(*ptrFirst)))
{
//it is the only way you should go back a position to write '\0' to
//over the non-alphabetic char
ptrFirst--;
*ptrFirst= '\0';
break;
}
}
else
{
//this is the second situation that the first char is indeed alphabetic char
ptrFirst ++;
ptrSecond ++;
//you just move to next without copy
if (*ptrSecond=='\0'&&(!isalpha(*ptrFirst)))
{
//until you find the last char is non-alphabetic
//you ten copy by over-writing '\0' to the non-alphabetic char
*ptrFirst = *ptrSecond;
break;
}
}
} }
//dictionary is your big char array
//arraysize is how many word you stored in dictionary
//wordsize is the max length of each word
void arrange(char* dictionary, const int arraySize, int wordSize)
{
void removeMark(char* word);
for (int i=0; i< arraySize; i++)
{
//actually you use the address of first char of word to make it as a string as paramenter
removeMark(&dictionary[i * wordSize]);
}
}
¡¡