does anyone know how to give the characters of a string numeric variables? so when i can print the numeric variables in decending order so the word is read backwards?
for example
hello h=1 e=2 l=3 l=4 0=5
olleh

your help would be very appreciated, a snippet would be awesome, or a written code would be very great.

Dani AI

Generated

Short answer: give each character its position (1..n) and either print the characters in descending index order or swap them in place. was right that a C string is an array; was right that you need the length first. Below are two safe, practical ways that avoid the signed/unsigned pitfalls of “for (i = len-1; i >= 0; --i)”.

Print reversed without modifying the string:

#include <stdio.h>
#include <string.h>

int main(void) {
    const char *s = "hello";         /* do not modify this literal */
    size_t len = strlen(s);
    size_t i = len;
    while (i--) {
        putchar(s[i]);
    }
    putchar('\n');
    return 0;
}

Reverse in place (use only on modifiable buffers; copy a literal first):

#include <string.h>
#include <stdlib.h>

char *reverse_copy(const char *s) {
    if (!s) return NULL;
    size_t len = strlen(s);
    char *buf = malloc(len + 1);
    if (!buf) return NULL;
    memcpy(buf, s, len + 1);
    char *a = buf, *b = buf + len - 1;
    while (a < b) {
        char tmp = *a; *a++ = *b; *b-- = tmp;
    }
    return buf;  /* caller must free() */
}

Notes and cautions: do not attempt to modify a string literal (undefined behavior); use char buf[] = "hello" or allocate and copy. Prefer size_t for lengths (see strlen) to avoid underflow; the while (i--) idiom iterates cleanly from len-1 down to 0. If the input may contain multi-byte UTF-8 characters, reversing bytes will break characters — decode code points first. enum is a compile-time construct and is not appropriate for assigning runtime positions. For reference on strlen and size_t, see strlen documentation.

Recommended Answers

All 6 Replies

enum will allow you to do that.

A string is basically just an array, why can't you simply start an index at the end and count down?

how would one do that?

I would start with this:

const char *s = "hello";
int i;

for ( i = 4; i >= 0; i-- )
  putchar ( s[i] );

Notice that Narue said start.
Unless you are working only with strings of four characters plus '\0' all the time, you'll see that for loop needs some more logic.
How can you figure before hand what the length of the string is to pass it to the for loop?

[erratum:]
>Unless you are working only with strings of four characters plus '\0' all the time

Since this might confuse the Original Poster I must correct myself. "Hello" is composed of five characters and the string terminator, and not four characters as previously stated.

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.