Example Code:
Arrays & Simple String Manipulation
// compstring.cpp : Defines the entry point for the console
application.
// main program for string_thing.
// Program illustrating the use of strings (char arrays) and some string
functions.
// Matthew Martin, 2004
#include "stdafx.h"
#include <stdio.h>
#include <conio.h>
#include "strngth.h" //The code for this header file can be
found here.
int main(int argc, char* argv[])
{
int tmp1=0;
int tmp2=0;
char choice='z';
char strng1[20];
char strng2[20];
char strng3[20];
char yn='z';
int result=0;
while (tmp1<1)
{
tmp2=0;
//clrscr();
printf ("Menu");
printf ("\n1: Compare two strings");
printf ("\n2: Copy string");
printf ("\n3: Length of string");
printf ("\n4: Concatenate two strings");
while (tmp2 <1)
{
printf("\n\nPlease enter a choice...\n");
fflush (stdin);
if (fscanf (stdin,"%[1234]c",&choice))
tmp2=1;
else
printf("\n Not a choice... ");
}
if (choice=='1')
{
printf ("\n Enter first string:-\n");
fflush (stdin);
scanf ("%s", strng1);
printf ("\n Enter second string:-\n ");
fflush (stdin);
scanf ("%s", strng2);
compare_strng(strng1, strng2);
}
else if (choice=='2')
{
printf ("\n Enter first string:-\n");
fflush (stdin);
scanf ("%s", strng1);
copy_strng(strng1, strng3);
printf ("\n Contents of new string:-");
printf ("\n%s", strng3);
}
else if (choice=='3')
{
printf ("\n Enter first string:-\n");
fflush (stdin);
scanf ("%s", strng1);
result=strng_lngth(strng1);
printf ("\nString length= %d", result);
result=0;
}
else if (choice=='4')
{
printf ("\n Enter first string:-\n");
fflush (stdin);
scanf ("%s", strng1);
printf ("\n Enter second string:-\n ");
fflush (stdin);
scanf ("%s", strng2);
cat_strng(strng1, strng2, strng3);
printf ("\nThe new string is:-");
printf ("\n %s", strng3);
}
printf ("\nAnother go? (y/n)");
yn=getch();
if (yn=='n')
{
tmp1=1;
}
else if (yn=='y')
tmp1=0;
}
return 0;
}
// compare two strings
int compare_strng (char strng1[], char strng2[])
{
int x=0;
int i=0;
int j=0;
for (i=0; strng1[i]!='\0'; i++)
{
}
for (j=0; strng2[j]!='\0'; j++)
{
}
if (i!=j)
{
printf ("\nThe two strings are not equal, man!");
}
else
{
printf ("\nThe two strings are of equal length, dood!");
}
return x;
}
// copy string into another string location.
int copy_strng (char strng1[], char strng3[])
{
int x=0;
for (x=0; strng1[x]!='\0'; x++)
{
strng3[x]=strng1[x];
strng3[x+1]='\0';
}
return 0;
}
// concatenation of two strings.
int cat_strng (char strng1[], char strng2[], char strng3[])
{
int y=0;
int x=0;
do
{
if (strng1[x]!='\0')
{
strng3[x]=strng1[x];
x++;
}
else if (strng2[y]!='\0')
{
strng3[x+y]=strng2[y];
y++;
}
}while (strng2[y]!='\0');
strng3[x+y]='\0';
return 0;
}
// String_Length
int strng_lngth (char strng1[])
{
int x=0;
int l=0;
do
{
if (strng1[x]!='\0')
{
x++;
}
}while (strng1[x]!='\0');
l=x+1;
return l;
}

by Matthew
Martin |