#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”

kena means spaces... ignore all the greek notes :P

Here's what my first-guess algorithm looks like:

1. Start copying characters from name to newName, keeping track of the number of spaces you encounter.
2. When you encounter the (m-1)th space, copy the remaining characters up through the (n-1)th space into a temporary buffer.
3. Copy the nth word from name into newName.
4. Find the first space in the temporary buffer and copy all the characters from that one on into newName.
5. Copy the mth word from the start of the temporary buffer into newName.
6. Copy the remaining characters from name into newName.

There's a (I think) better algorithm, but it involves trampling on the last half of newName instead of using a temporary buffer... I can't work out the details in my head and it would probably just be confusing anyway.

#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 i=0,kena=0,k=0,l,j;
    char temp[]="";
    while (kena!=m-1)  //mexri n ftasoume stin prwti le3i gia swap antigrafoume
    {                  //tous char tou name mexri ekei sto newName
        newName[i]=name[i];
        if (name[i]==' ')
        {
            kena++;   //metrame k ta kena
        }
        i++;
    }
    j=i;
    while (name[j]!=' ')   //otan ftanw sti le3i tin apo8ikeuw mexri n ftasw sto epomeno ' '
    {
        temp[k]=name[j];
        k++;
        j++;
    }
    for(l=i;l<strlen(name);l++)
    {
        if (name[l]==' ')
        {
            kena++;
            if (kena==n-1)
            {
                break;  //vriskw pou 3ekinaei i deuteri le3i gia swap
            }
        }
    }
    while (name[l+1]!=' ')
    {
        newName[i]=name[l+1];   //tin antigrafw sti sunexeia tou newName k vazw k to ' '
        i++;
        l++;
    }
    newName[i]=' ';
    i++;
    newName[i+1]='\0';
    return newName;
}



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("\nDwste tous ari8mous 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%d",&m,&n);
    }
    swapWords(string,swappedstring,m,n);
    free(string);
    getchar();
    getchar();
    return 0;
}

that's what I have so far... :( only the words before the first swap and then the second chosen words...

Well, you can try this method: This involves extra space though.

Algorithm:

1) Extract words into a buffer( i have used a 2D array)
2) Mark indices
3) Swap indices.
4) Print as per indices, so that the words will be swapped.

char *arr = "hello world bye world"; // the string
char arr_store[10][10];	//  Now, use sscanf() and store words in this array
int arr_index[10]; // store indices

So, basically, we store all words into a 2D array and while printing, we print in the order in which you want.

/* so, i will exchange second and third word */
	int exch1 = 1;
	int exch2 = 2;

	for (i = 0, c = 0; *arr != '\0'; i++) {
		sscanf(arr, "%s", arr_store[i]);
		arr_index[i] = i; // set index
				
		// go to the next space.
		c = 0;
		while ( (*arr != ' ') && (*arr != '\0')) {	
			c++;	
			arr++;			
		}							
		if (*arr++ == '\0') {
			arr -= (c+1);
			sscanf(arr, "%s", arr_store[i]);			
			break;
		}
			
	}
		
	// swap indices. 
        int temp = arr_index[exch1];
	arr_index[exch1] = arr_index[exch2];
	arr_index[exch2] = temp;

	// now print	
	for (i = 0; i < 4; i++) {
		 printf("%s" arr_store[arr_index[i]]); 	
	}

eg:

Initially,

hello world bye world
  0     1    2    3    <--arr_index[]

Now, swap elements in arr_index[], thus giving:

  0     2    1     3

So, when you print, it is reversed.

Can this be done for your case?

On the same note, requiring less extra space than myk45's suggestion and only somewhat more computationally intensive than mine, keep an array of pointers. Step through the string, and, every time you pass a space, overwrite it with a 0 and store a pointer to the next character in the array.

When you're done, you'll have an array of pointers to null-terminated strings.

temp = array[m-1];
array[m-1] = array[n-1];
array[n-1] = temp;

and loop through the array, printing each one and spaces between each.

@Trentacle

Well, you will be needing to allocate memory to the pointers right? So, won't the memory requirements be the same?

@Trentacle

Yeah, i got your point. Yes. That would be a better approach.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.