Reversing a string in c with recursion - c

I have written code to reverse a string in c... it works fine but I can't return the reversed string in the main() function.
#include<stdio.h>
main()
{
char a[17]="abcdefg";
reverse(a);
printf("\n");
system("PAUSE");
}
int reverse(char *a)
{
if(*a!='\0')
{
reverse(a+1);
}
printf("%c",*a);
}
it prints the reversed string but I want the reversed string in main(). How can I do this?

Following is one way to reverse string using recursion!
#include <stdio.h>
#include <string.h>
void rev_str_recursive(char arr[], size_t iStart, size_t iLast)
{
if( iStart < iLast )
{
//swap
char temp = arr[iStart];
arr[iStart] = arr[iLast];
arr[iLast] = temp;
rev_str_recursive(arr, ++iStart, --iLast);
}
}
void main()
{
char cArray[] = {"A quick brown fox jumps over a lazy dog"};
rev_str_recursive(cArray, 0, strlen(cArray)-1);
}

You need to modify the string, i.e. the input buffer to reverse(), instead of just printing it.
Doing this recursively seems a bit obnoxious, but should of course be possible.
Basically, I guess the printing becomes an assignment, something like this:
Base: The reversal of an empty string is the empty string.
Step: The reversal of a string begins by swapping the first and last characters, then recursing over the remainder of the string.

Here is another way to reverse a string using recursion:
void reverseString(char* dest, char *src, int len) {
if (src == NULL || len == 0)
return;
reverseString(dest, src + 1, len - 1);
strncat_s(dest, len + 1, src, 1);
}
You can call like that:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define STRING "Let's try this one."
#define SIZE 20
void main() {
char* src = (char*)malloc(SIZE);
char* dest = (char*)malloc(SIZE);
strcpy_s(dest, SIZE, "");
strcpy_s(src, SIZE, STRING);
reverseString(dest, src, strlen(src));
/* Do anything with dest. */
// printf("%s\n", dest);
free(src);
free(dest);
}

This code is not executable :(
You define int reverse but reverse function doesnt return any value
instead use this (using void):
#include<stdio.h>
main()
{
char a[17]="abcdefg";
reverse(a);
printf("\n");
system("PAUSE");
}
void reverse(char *a)
{
if(*a!='\0')
{
reverse(a+1);
}
printf("%c",*a);
}

#include <iostream>
using namespace std;
reverse( char *str)
{
if (*str!='\0')
{
reverse(str+1);
cout<<*str;
}
//cout<<*str when i am just printing here then why this is printing after one space ??
}
int main()
{
string a ;
cin>>a;
reverse(&a[0]);
return 0;
}

a little change in Emre Can Kucukoglu's answer . . .
we can eliminate strncat_s
void revstr_rec(char *sstr, char *dstr, int len)
{
int i = 0;
if((! *sstr) || (! len) )
return;
revstr_rec(sstr + 1, dstr, len - 1);
dstr[len - 1] = *sstr;
return;
}
int main()
{
char *sstr = NULL;
char *dstr = NULL;
sstr = malloc(16);
if(! sstr) {
printf("no memory . . .\n");
return 0;
}
strcpy(sstr, "hello world !");
printf("sstr: %s\n", sstr);
dstr = malloc(16);
if(! dstr) {
printf("no memory . . .\n");
return 0;
}
revstr_rec(sstr, dstr, strlen(sstr));
printf("dstr(recursive): %s\n", dstr);
free(sstr);
free(dstr);
return 0;
}

#include <stdio.h>
#define MAX 100
int main()
{
char str[MAX], *rev;
scanf("%s", str);
rev = reverse(str);
printf("The reversed string is : %s\n", rev);
return 0;
}
char *reverse(char ch[])
{
static char r[MAX];
static int i=0;
if(*ch == '\0') return "";
else
{
reverse(ch+1);
r[i++]=*ch;
}
return r;
}

A simple way with left and right index
void main()
{
char* str = (char*)malloc(strlen("somestring")+1);
strcpy(str, "somestring");
int leftIndex = 0;
int rightIndex = strlen(str) - 1;
printf("%s\n", ReverseString(str, leftIndex, rightIndex));
free(str);
}
char* ReverseString(char* str, int leftIndex, int rightIndex)
{
if (leftIndex == rightIndex || leftIndex == (rightIndex +1)) {
return str;
}
// flip letters
char leftLetter = *(str + leftIndex);
char rightLetter = *(str + rightIndex);
*(str + leftIndex) = rightLetter;
*(str + rightIndex) = leftLetter;
return ReverseString(str, leftIndex+1, rightIndex -1);
}

use sprintf it will print your reversed string into buffer.
#include<stdio.h>
char *b;
main()
{
char a[17]="abcdefg";
char buffer[17];
buffer[0]= '\0';
b = buffer;
reverse(a);
printf("%s\n",buffer);
}
int reverse(char *a)
{
if(*a!='\0')
{
reverse(a+1);
sprintf(b,"%c",*a);
b++;
}
}

void palindromo(char *s)
{
if(s[0] != '\0'){
palindromo(s+1);
printf("%c", s[0]);
}
}
This is a small recursive function who print the string inverted.

#include<stdio.h>
#include<string.h>
void rev(char *);
int main()
{
char s[]="Hello";
printf("\n%s",s);
rev(s);
printf("\n%s",s);
return 0;
}
void rev(char *s)
{
static int i=0;
static int j=0;
if(j==0) //since static variable can be intitialized
{ //only with a constant literal,to store
j=strlen(s)-1; //length-1 in 1st function call, we can use
} //this trick.(condition satisfied only in 1st
//function call)
if(i<j)
{
char temp;
temp=s[i];
s[i]=s[j]; //Analogous to for(i=0,j=l-1;i<j;i++,j--)
s[j]=temp; // { //swap code }
i++;
j--;
rev(s);
}
}

#include<stdio.h>
void reverse(char *a);
main()
{
char a[17]="abcdefg";
reverse(a);
printf("\n");
system("PAUSE");
}
void reverse(char *a)
{
if(*a!='\0')
{
reverse(a+1);
}
printf("%c",*a);
}

Related

Getting jargon before actual data when printing char pointer

I'm writing a program that implements the Alberti Cipher, and when testing, the final print always gives a string of jargon before the actual encryption. Right now its printing \x80\x16G\xbf\xfe\x7fKHOORZRUOG, with KHOOR..... being the actual encryption. Any help appreciated :)
#include <stdio.h>
#include <stdlib.h>
int letterToNumber(char letter){
char str[2] = { letter };
int num = strtol( str, NULL, 36 ) - 10;
return num;
}
int getSize (const char * s) {
const char * t;
int size = 0;
for (t = s; *t != '\0'; t++) {
size++;
}
return size;
}
char numToChar(int numInp){
numInp=numInp+65;
char returnChar=(char)numInp;
return returnChar;
}
void encrypt_alberti(const char *message,const char *inner_ring, int initialShift,int periodicShift,int periodLength,char **result){
//sets initial shift
int numArray[25];
int count=0;
int shiftCount=0;
for(int i = 0; i < 26; ++i) {
numArray[i]=(i+initialShift)%26;
}
//encrypts each character and prints
int messageSize=getSize(message);
char encryptedMessage[messageSize];
for(int i=0; i<messageSize;i++){
count++;
if(periodicShift!=0){
if(count%periodicShift==0){
shiftCount++;
}
}
else{
periodLength=0;
}
char toBeEncrypted=message[i];
int charNumber=letterToNumber(toBeEncrypted);
int encryptedNum=numArray[(charNumber+(shiftCount*periodLength))%26];
char encryptedChar=numToChar(encryptedNum);
strncat(encryptedMessage, &encryptedChar, 1);
}
char* p1=malloc(sizeof(encryptedMessage));
strcpy(p1,encryptedMessage);
*result=p1;
}
void main(void) {
const char *example_message = "HELLOWORLD";
const char *example_inner = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char *encrypted_message = NULL;
encrypt_alberti(example_message, example_inner, 3, 0, 1, &encrypted_message);
printf("message is %s\n", encrypted_message);
printf("-----------------");
free(encrypted_message);
}
}

Cut out section of a string with another string

I got this part of a C program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void){
char *mRNA = spleissen("AUAGUAAAAGCUCUGUUUAGGAGA", "GU", "AG");
printf("mRNA: %s\n", mRNA);
free(mRNA);
return 0;
}
I have to write the function spleissen which should work like this: it cuts out a string which goes from a GU to an AG and everything in between those two. So the program output is:
mRNA: AUACUCUGAGA
I don't really know how I can cut those parts out.
I am not allowed to use includes other than stdio, string and stdlib.
char *spleissen(const char *src, const char *start, const char *end){
size_t len = strlen(src);
char *s, *e, *ret, *work;
ret = work = malloc(len + 1);
strcpy(work, src);
len = strlen(end);
while(s = strstr(work, start)){
if((e = strstr(s, end))==NULL)
break;//delete upto last?
memmove(s, e + len, strlen(e+len)+1);
work = s;
}
return ret;
}
I think you can simply do this:
char *spleissen(char *array, char *G, char *A)
{
int l=strlen(array);
int i, j=0;
char returnstr[10010];
int b=0;
for(i=0; i<l; i++)
{
if(G[0]==array[i] && G[1]==array[i+1])
{
b=1, i++;
continue;
}
else if(A[0]==array[i] && A[1]==array[i+1] && b==1)
{
b=0, i++;
continue;
}
if(b==0)
{
returnstr[j]=array[i];
j++;
}
}
return returnstr;
}

Removing characters in c string

How to remove a specific character from a string in c ?
Eg: if the string is "abcd"
i need to remove the character of index 1
then the result should be , "acd"
My attempt:
void removeSymbol(char *line){
int i,j; char c;
for(i=0;i<strlen(line);i++){
c = *(line +i);
if(!(isdigit(c)||isalpha(c))){ strcpy((line+i),(line+i+1)); }
}
printf("%s\n",line);
}
static inline void removeSymbol(char *line, size_t index){
memmove(&line[index], &line[index+1], strlen(&line[index]));
//printf("%s\n",line);
}
I have changed the prototype of removeSymbol API. I hope this below code will meet your requirements
void removeSymbol(char *line, int index)
{
//Added as per comments
if ( (index > 0 ) && ( index <= strlen (line) ) )
{
//index-> index which needs to be removed.
// +1 is added in memmove last argument to move '\0' character also
memmove (&line[index-1], line + index, strlen (line)-index +1 );
}
}
int main(void){
char symbol [] = "abcdefgh";
removeSymbol (symbol, 8);
printf ("%s\n", symbol);
}
#include <stdio.h>
#include <string.h>
void removSymbol(char *,int);
main()
{
int index=1;
removSymbol("abcd",index);
}
void removSymbol(char *line,int index)
{
int i;
for(i=0;i<strlen(line)-1;i++)
{
if(i<index)
{
*(line+i) = *(line +i);
}
else
{
*(line+i) = *(line+i+1);
}
}
*(line+i+1)='\0';
printf("%s\n",line);
}

Wrong output in my stringreverse program. what is fault in my code?

#include<stdio.h>
#include<conio.h>
#include<string.h>
char* strreverse(char*);
int main()
{
char *rev_string;
char *name="computer";
clrscr();
rev_string=strreverse(name);
printf("%s", rev_string);
getch();
return 0;
}
char* strreverse(char *name)
{
int length=strlen(name);
char *ptr;
char *rstr;
for(ptr=name+(length-1);ptr>=name;ptr--)
{
*rstr=*ptr;
printf("%c",rstr);
rstr++;
}
*(rstr)=NULL;
return rstr;
}
the above is my code. i tried to write a program for string reverse without using arrays. But i am not getting the output retupmoc. what is wrong in my code? how to insert null char in char*?
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
char* strreverse(const char*);
int main(){
char *rev_string;
char *name="computer";
clrscr();
rev_string=strreverse(name);
printf("%s\n", rev_string);
free(rev_string);
getch();
return 0;
}
char* strreverse(const char *name){
int length=strlen(name);
const char *ptr;
char *ret, *rstr = malloc(length + 1);
if(ret=rstr){
for(ptr=name+length;ptr != name;){
*rstr++ = *--ptr;
}
*rstr = '\0';
}
return ret;
}
You did not allocate memory to hold your reversed string. Try
char *rstr = calloc(1, length+1);
Also it should be
printf("%c", *rstr); // dereference
*(rstr)= '\0'; // instead of NULL
Here you find sweet and short solution for string reverse:
#include<stdio.h>
#include<string.h>
int strreverse(char* , char*);
int main()
{
char rev_string[10] = {0};
char name[10]="computer";
strreverse(name, rev_string);
printf("%s\n", rev_string);
return 0;
}
int strreverse(char *name, char *rStr)
{
int i = 0;
int length = strlen(name);
while(i < length)
{
rStr[i] = name[length-i-1];
i++;
}
return 0;
}
Try to run and have fun.

Right Justified Zero filled String in C

I want to right justify a string value with zero filled on left hand side. I have written following code but it prints white space instead of 0.
#include<stdio.h>
int main()
{
char s[4]="PJ";
printf("%04s",s);
}
Output: " PJ"
I need output as "00PJ".
You can do something like this :
#define MIN_LEN 4
if (strlen(s) < MIN_LEN) {
printf("%0*d%s", MIN_LEN-(int)strlen(s), 0, s);
}
else {
printf("%s", s);
}
Don't forget to include <string.h>
Edit :
To explain our discussion about buffer overflow, just try this piece of code :
int main()
{
struct
{
char s[4];
int i;
} test;
test.i = 0x12345678;
strcpy(test.s,"PJHA");
printf("Output =%s\nTest =%x",test.s,test.i);
}
Output :
Output =PJHA
Test =12345600
If you change the size to 5, the code is corrected and the stack following your string is not corrupted.
Here is the short line code answer for my question:-
This will take care of any length of input variable like s = "J", s="JH", s="JHA", s="PJHA"
and corresponding output will be "000J", "00JH", "0JHA", "PJHA" .
#include<stdio.h>
#include<string.h>
int main()
{
char s[4],s2[4];
strcpy(s,"JH");
sprintf(s2,"%04s",s);
memset(s2,'0',4-(int)strlen(s));
printf("Output =%s\n",s2);
}
Output =00JH
Appreciate the above simpler solution while giving an alternative more manual one:
#include<stdio.h>
#include<string.h>
void print(char *s, int ncount)
{
if(s == NULL) return;
int len = strlen(s);
if(len > ncount) printf("%s", s);
else {
for(int i = 0; i < ncount - len; ++i)
printf("0");
printf("%s", s);
}
}
int main()
{
char s[4]="PJ";
print(s, 4);
return 0;
}
#include <stdio.h>
#include <string.h>
int main(){
char s[5]="PJ";
char padding[sizeof(s)] = {0};
int width = sizeof(padding)-1;
memset(padding, '0', width);
width -= strlen(s);
//printf("%.*s%s\n", (int)(4-strlen(s)), "0000", s);
printf("%.*s%s\n", width, padding, s);
return 0;
}

Resources