#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int getNumWords(char *name)
{
int i,numofwords=0;
for(i=0;i<strlen(name);i++)
{
while (name[i]==' ')
{
i++; //pernaei ta kena osa k an einai. akoma k an einai stin arxi k sto telos
}
if (((i==0)&&(name[i]!=' '))||(i>=1)&&((name[i-1]==' ')&&(name[i]!=' ')&&(name[i]!='\0')))
{ //i 1i sun8iki einai gt an to i itan 0 8a pigaine name[-1] xwris auti
numofwords++; //sti 2i an exw ' ' k meta char tote metraei le3i
} //alla to \0 metraei san char opote an to string teleiwne se ' ' 8a to metrouse san le3i
}
return numofwords;
}
void printWord(char *name, int k)
{
int i=0,kena=0;
if (kena==k-1) //an zitisw tin 1i le3i tote ta kena 8a einai 0
{
while (name[i]==' ')
{ //ektos k an 3ekinaei apo ' ' to string pou tote apla ta pername ta prwta ' '
i++;
}
while (name[i]!=' ')
{
printf("%c",name[i]);
i++;
}
}
else
{
for(i=0;i<strlen(name);i++)
{
if (i==0)
{
while (name[i]==' ') //diaforetika to upologizoume me ta kena k pername pali ta prwta ' ' an uparxoun
{
i++;
}
}
if (name[i]==' ')
{
kena++;
if (kena==k-1) //otan ftasw sta kena pou prepei vgainw apo tin for
{
break;
}
}
}
i++;
while ((name[i]!=' ')&&(name[i]!='\0')) //ektupwnw ti le3i mexri to epomeno keno i mexri to \0 an einai i teleutaia
{
printf("%c",name[i]);
i++;
}
}
}
void swapWords (char *name,char *newName,int m,int n)
{
;
}
int main(void)
{
char *string,swappedstring[]="";
int i=0,c=0,words,k,m,n;
string=(char*)malloc(100*sizeof(char));
if (string==NULL)
{
printf("No Memory Available\n");
exit(0);
}
printf("Dwste ena string to polu 100 xaraktirwn: ");
gets(string);
while ((i<strlen(string))&&(string[i]!='\0'))
{
c++;
i++;
}
string=(char*)realloc(string,c*sizeof(char));
words=getNumWords(string);
printf("Dwste ton ari8mo mias apo tis %d le3eis pou dwsate prin: ",words);
scanf("%d",&k);
while ((k<=0)||(k>words))
{
printf("Dwsate la8os ari8mo! Dwste apo 1 mexri %d: ",words);
scanf("%d",&k);
}
printWord(string,k);
printf("Dwste ton ari8mo 2 le3ewn apo tis %d: ",words);
scanf("%d%d",&m,&n);
while ((m<=0)||(m>words)||(n<=0)||(n>words)||(m==n))
{
if (m==n)
{
printf("Dwste diaforetikes le3eis!");
}
printf("Dwsate la8os ari8mous! Dwste apo 1 mexri %d kai gia tis 2 le3eis: ",words);
scanf("%d",&k);
}
swapWords(string,swappedstring,m,n);
free(string);
getchar();
getchar();
return 0;
}
I don't know what to do with the 3rd function... the user gives a string (we assume words are separated by one space). though I did the other functions for every string.. for the 3rd function we give 2 numbers which represent two words of the string and the string and the function must swap those two words and then copy the new string to newName.. I don't know what to do! help me! it's urgent!
here is an example:
swapWords (“test Program C”, 2, 3, newName)
newName will be “test C Program”