{"id":5541,"date":"2022-09-24T00:01:09","date_gmt":"2022-09-24T07:01:09","guid":{"rendered":"https:\/\/c-for-dummies.com\/blog\/?p=5541"},"modified":"2022-09-10T15:19:35","modified_gmt":"2022-09-10T22:19:35","slug":"reversing-a-string","status":"publish","type":"post","link":"https:\/\/c-for-dummies.com\/blog\/?p=5541","title":{"rendered":"Reversing a String"},"content":{"rendered":"<p>The C language is weak when it comes to strings. Even the paltry assortment of <code>string.h<\/code> manipulation functions lacks quite a few tricks that are readily available to other languages. Among them is a function to reverse a string. So why not code your own?<br \/>\n<!--more--><br \/>\nI call my string reversing function <em>strrev()<\/em>. In this function, storage is allocated for a new string, then it&#8217;s filled forward while processing the original string backwards. Figure 1 illustrates what my words fail to describe.<\/p>\n<div id=\"attachment_5542\" style=\"width: 510px\" class=\"wp-caption aligncenter\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-5542\" src=\"https:\/\/c-for-dummies.com\/blog\/wp-content\/uploads\/2022\/09\/0924-figure1.gif\" alt=\"\" width=\"500\" height=\"251\" class=\"size-full wp-image-5542\" \/><p id=\"caption-attachment-5542\" class=\"wp-caption-text\">Figure 1. The process of reversing a string, backwards-copying characters from one to the other based on the string&#8217;s length.<\/p><\/div>\n<p>Here is the <em>strrev()<\/em> function illustrated in code:<\/p>\n<h3><a href=\"https:\/\/github.com\/dangookin\/C-For-Dummies-Blog\/blob\/master\/2022_09_24-Lesson.c\" rel=\"noopener\" target=\"_blank\">2022_09_24-Lesson.c<\/a><\/h3>\n<pre class=\"screen\">\r\n#include &lt;stdio.h&gt;\r\n#include &lt;stdlib.h&gt;\r\n#include &lt;string.h&gt;\r\n\r\nchar *strrev(char *s)\r\n{\r\n    int len,i;\r\n    char *reversed;\r\n\r\n    <span class=\"comments\">\/* obtain string character count *\/<\/span>\r\n    len = strlen(s);\r\n\r\n    <span class=\"comments\">\/* +1 for the null character *\/<\/span>\r\n    reversed = malloc( sizeof(char) * len +1 );\r\n    <span class=\"comments\">\/* if memory allocated, fill it with\r\n       the reversed string *\/<\/span>\r\n    if( reversed!=NULL )\r\n    {\r\n        s += len -1;        <span class=\"comments\">\/* last char *\/<\/span>\r\n        i = 0;                <span class=\"comments\">\/* forward index *\/<\/span>\r\n        while(len)\r\n        {\r\n            *(reversed+i) = *s;        <span class=\"comments\">\/* fill *\/<\/span>\r\n            i++;            <span class=\"comments\">\/* move index forward *\/<\/span>\r\n            len--;            <span class=\"comments\">\/* loop counter *\/<\/span>\r\n            s--;            <span class=\"comments\">\/* backward offset *\/<\/span>\r\n        }\r\n        <span class=\"comments\">\/* cap the string *\/<\/span>\r\n        *(reversed+i) = '\\0';\r\n    }\r\n\r\n    return(reversed);\r\n}\r\n\r\nint main()\r\n{\r\n    char string[] = \"Here is your sample string\";\r\n\r\n    printf(\"Original: %s\\n\",string);\r\n    printf(\"Lanigiro: %s\\n\",strrev(string));\r\n\r\n    return(0);\r\n}<\/pre>\n<p>At Line 11, the string&#8217;s length is obtained. This value, <code>len<\/code>, is used to allocate the new string (Line 14), plus one more character for the terminating null character.<\/p>\n<p>Upon success, pointer <code>s<\/code> is reset to the end of the string, minus one (because the offset starts at zero). Variable <code>i<\/code> is set to zero. A <em>while<\/em> loop spins for the length of the original string, copying characters from <code>*s<\/code> (the original, backwards) to <code>*(reversed+i)<\/code> (the duplicate, in a forward direction). (Figure 1 illustrates how <code>s<\/code> and <code>i<\/code> manipulate the two string buffers.) (Sorry for all the parentheticals.)<\/p>\n<p>The new, reversed string is capped with a null character at Line 29. String <code>reversed<\/code> is returned at Line 32. If memory allocation fails, a <code>NULL<\/code> value is returned for <code>reversed<\/code>. I don&#8217;t check for this condition in the <em>main()<\/em> function.<\/p>\n<p>Here is the output:<\/p>\n<p><code>Original: Here is your sample string<br \/>\nLanigiro: gnirts elpmas ruoy si ereH<\/code><\/p>\n<p>I assume other ways exist to reverse a string. At some point, however, the code must work the original string backwards to fill (forwards) the new string.<\/p>\n<p>Now that you have a backwards string, the obvious question is what to do with it? Hmmm.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I&#8217;m shocked! I&#8217;ve not shared this function before. <a href=\"https:\/\/c-for-dummies.com\/blog\/?p=5541\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[],"class_list":["post-5541","post","type-post","status-publish","format-standard","hentry","category-main"],"_links":{"self":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/5541","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=5541"}],"version-history":[{"count":6,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/5541\/revisions"}],"predecessor-version":[{"id":5550,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/5541\/revisions\/5550"}],"wp:attachment":[{"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=5541"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=5541"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/c-for-dummies.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=5541"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}