Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

reversing character arrays

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Can anyone help me set up an array to be able to do this example:

INPUT:
The cat sat on the mat
What?

OUTPUT:
tam eht no tas tac ehT
?tahW

Thanks.
 
Here(note - untested for syntax, but it should work):[tt]
reverse(s) /* reverses strings in place */
char *s;
{
char c, *t;
int linelen();

for (*t = s + linelen(s) - 1; s < t; s++, t--)
{
c = *s;
*s = *t;
*t = c;
}
}

linelen(s)
char *s;
{
char *p = s;

while ( (*p) && (*p != '\n') )
p++;
return(p-s);
}
[/tt]

call it with a while loop(you supply readline or an equivelent):[tt]
char *s;
while ( s = readline() )
{
reverse(s);
printf(&quot;%s&quot;, *s);
}
[/tt]
and voilá.
the logic is as follows: s starts at the first element of the array, t starts at the last, not including the '\0' or the '\n'. then, their values will be switched. lastly, s and t will each be incremented one towards the middle until they pass each other, thus switching all the characters.
HTH &quot;If you think you're too small to make a difference, try spending a night in a closed tent with a mosquito.&quot;
 
Simplier...
...

int reverse(char s[],int *count) {this function number of chars placed on the screen}
{
int q = 0;
for (q = *count;q >= 0;q ++)
{
printf(&quot;%c&quot;,s[q-1]);
q++;
}
printf(&quot;\n&quot;);
return (q++);
}

...
char s[255];
printf(&quot;Enter a sentence: &quot;);
gets(s);
l = strlen(s);
printf(&quot;Reversed sentence is: &quot;);
int temp(0);

for (int q = 0;q < l;q ++)
{
if ((s[q] == '\n') || (s[q] == '\0'))
temp = reverse(s,&(q - temp-1));
}


...
Best Regards,

aphrodita@mail.krovatka.ru {uiuc rules}
 
the simpliest...

void PrintReverse(char *s)
{
int i,l;
l = strlen(s);
for (i=l-1; i>=0; i--)
putch(s);
printf(&quot;\n&quot;);
return;
}

void main()
{
char line[100][100];
char ch;
int i,n=0;
printf(&quot;Enter a set of sentence:\n&quot;);
while (1)
{
ch=getchar();
if (ch=='\n') break;
line[n][0]=ch;
i=1;
while ((ch=getchar())!='\n') line[n][i++]=ch;
line[n]='\0';
n++;
}
for (i=0;i< n;i++)
PrintReverse(line);
return;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top