10/18/08

Strings and Pointers in C - Part 1

This is another simple program written in C programming language.
The purpose of this program is more educational than useful to anyone.
So, here is the explanation of what it does.
It reads two strings from the user into two tables of chars of size N where N is defined as 10 in this examples.
When the program read both strings it prints the two strings in one then reverse them.
Then prints another string a little more complicated. The last string contains the characters of the first one but when characters at position i of the two strings are the same it places a * as the i-th element. Then replaces continues * with one * and prints the string.
Well, I made three implementations of this "problem".
The first one uses char tables.
The second one uses tables too but instead of getting access directly to table's elements it uses pointers.
The third one uses only pointers.
That's why I said is for educational purposes. The interested reader can find the differences between them and understand better hoe to use pointers.

here is the first implementation.(with tables only)

#include <stdio.h>
#define N 10

int main(int argc, char* argv[]) {
char a,s1[N],s2[N],s[N+N-1];
/* s=s1+s2, s=s2reversed+s1reversed, s=* */
int i,j,k; /* i for s1,j for s2, k for s */

/*input and output s1 & s2 */
printf("Give First String : ");
scanf("%s",s1);
printf("String1 is %s \n",s1);

printf("Give Second String: ");
scanf("%s",s2);
printf("String2 is %s\n",s2);
printf(" ---------------\n");

/* copy s1 and s2 to s */
for(i=0; s1[i]!='\0' ; i++) {
s[i]=s1[i];
}
for(j=0; s2[j]!='\0' ; i++,j++) {
s[i]=s2[j];
}
s[i]='\0';
printf("Two strings together:\n%s\n",s);

/* s = s2reversed + s1 reversed */
/* may use strlen() instead */
for(j=0; s2[j]!='\0' ; j++) {} /* j = end of s2 */
for(i=0; s1[i]!='\0' ; i++) {} /* i = end of s1 */
for (k=0,j--; j>=0 ; k++,j--) {
s[k]=s2[j];
}
for (i--; i>=0 ; i--,k++) {
s[k]=s1[i];
}
s[k]='\0';
printf ("Two strings reversed:\n%s \n");
printf("\n ---------------\n",s);

/*
replace same chars with * and replace
multiple * with one *
*/
i=0;
j=0;
if (s1[i]==s2[i]){ s[i]='*' ; }
else {
s[i]=s1[i];
}
i++;j++ ;
for (;i<N;i++,j++) {
if(s1[i]=='\0') { break;}
else {
if (s1[i]==s2[i]) {
if (s[j-1]=='*') {j--;}
else {s[j]='*';}
}
else {
s[j]=s1[i];
}
}
}
s[j]='\0'; //end of s
printf("Same char = *:\n%s",s);
printf("\n -----*END*-----\n");
}


As I decided to split this post so the reader can open in different windows and compare the implementations,
you can continue with the Strings and Pointers in C - Part 2 including second and third implementations is here.
Thank you for visiting, reading and commenting.

No comments: