I'm trying to write a code where I input a String and I get it reversed. I.e.: "nokia" to "aikon".
I already have it in a way, but now I want to use the function strlen()
to get the original String's length and create the new one based on that length.
Here is the code:
void main(void)
{
char palavra[10];
char palavra2[10];
int i;
int k;
printf("Introduza uma string: \n");
scanf("%[^\n]", palavra);
for( i = 0, k = strlen(palavra) - 1 ; i <= k; i++, k--)
{
palavra2[k] = palavra[i];
}
printf("\nString invertida: %s", palavra2);
}
However all I get from my printf()
is a "?". What am I doing wrong?
your loop indexes are running the opposite ways so they meet in the middle and the loop stops when i <= k
: half of the string is not inverted. Just test i
against strlen(palavra)
Plus you have to null-terminate your string:
int len=strlen(palavra);
for( i = 0, k = len - 1 ; i < len; i++, k--)
{
palavra2[k] = palavra[i];
}
palavra2[len]='\0';
(and you'd better store the value of strlen(palavra)
so you have to compute it only once)
Try this simple reverse function:
/* reverse: reverse string s in place */
void reverse(char s[])
{
int c, i, j;
for (i = 0, j = strlen(s)-1; i < j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
To integrate it into your code:
void main(void)
{
char palavra[10];
int c, i, j;
/* read the string */
printf("Introduza uma string: \n");
scanf("%[^\n]", palavra);
/* null-terminate the string */
palavra[strlen(palavra)] = '\0';
/* reverse the string */
for (i = 0, j = strlen(palavra)-1; i < j; i++, j--) {
c = palavra[i];
palavra[i] = palavra[j];
palavra[j] = c;
}
printf("\nString invertida: %s", palavra);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With