C Puzzles

yet another place for C puzzles

Wednesday, May 19, 2010

 

How do you reverse the words in a string?

How do you reverse the words in a string?

"My name is Yet Another Software Junk"
to
"Junk Software Another Yet is name My"


answer:
1. first reverse the string
"My name is Yet Another Software Junk" to
"knuJ erawtfoS rehtonA teY si eman yM"

2. reverse word by word now
"knuJ erawtfoS rehtonA teY si eman yM" to
"Junk Software Another Yet is name My"



Comments:
I can Give 2 more soln:
1)Do it recursively,first call the reverse function again n again from start to end and when function returns copy each char in a separate array or u may try printing it

2)Use divide n Conquer:swap ith element with (n-i)th element..for array with odd element order is of O(logn) but for even it is lineraly recursive and is of order O(n^2)
 
/**
I am a boy -> boy a am I

*/
#include
#include
#include
int main()
{
int i, j, n, temp, temp_i, cnt;
//char *array = "Samsung";
char array[1000];
char newarr[strlen(array)];
printf("Enter The String: \n");
gets(array);

for(i = (strlen(array)-1), n = 0, j = 0; i >= 0; i--)
{
if( array[i] != ' ')
{
n++;
}
else
{
temp = n;
temp_i = i;
for(n = 0; n <= temp; n++)
{
// i = i + 1;
newarr[j++] = array[i++];
}
i = temp_i;
n = 0;
}

if(i == 0)
{
newarr[j++] = ' ';
newarr[j++] = array[i];
}


//newarr[j++] = array[i];
}
newarr[j] = '\0';
cnt = 0;
for(j = 0; j <= (strlen(newarr)-1); j++)/*This is not required just do some R n D*/
{
newarr[j] = newarr[++cnt];
}
// printf("The first element is %c \n", newarr[1]);
puts(newarr);
return 0;
}
 
public class ReverseWords
{
public static void main(String[] args)
{
String line = "My name is Yet Another Software Junk";
char[] lineChars = line.toCharArray();
char[] out = new char[lineChars.length];
int destPos = 0;
int wordLength = lineChars.length;

for (int i = lineChars.length - 1; i >= 0; --i)
{
if (Character.isWhitespace(lineChars[i]) || i == 0)
{
arrayCopy( lineChars,
i == 0 ? 0 : (i + 1),
out,
destPos,
i == 0 ? wordLength : (wordLength - i - 1));
wordLength = i;
destPos = lineChars.length - i;
}
}
System.out.println(new String(out));
}
static void arrayCopy(char[] src, int srcPos, char[] dest, int destPos, int length)
{
for (int i = 0; i < length; ++i)
{
dest[destPos++] = src[srcPos++];
}
}
}
 
Post a Comment

Subscribe to Post Comments [Atom]





<< Home

Archives

July 2005   August 2005   October 2005   December 2005   March 2006   June 2006   July 2006   December 2006   February 2007   June 2007   March 2010   May 2010  

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]