Manual Reverse string [CHALLENGE]

Jan 30, 2020 at 12:21am
I was challenged to create a function that will reverse a given string, and unfortunately running out of time. this is my last resort


I was restricted to use other functions and add new lines.

I was challenged to finish ONLY this template.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  #include <iostream>
using namespace std;
void stringRev(char *s);

int main()
{
	char str[]="Happy Day";
	cout << stringRev(str);
	system ("pause > 0");
	return 0;
}

char* stringRev(char *s)
{	
	char* tmp;
	tmp = new char;
	int i, cnt(0);
	for( ; ; )
	{
		cout <<  s[i] << endl;
		cnt++;
	}
	for( ; ; )
	{
		tmp[] = s[   - - ];
	}
	tmp[i]='\0';
	return tmp;
	
	
}
Jan 30, 2020 at 2:22pm
well, you failed, better luck next time

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
cout << stringRev(str); //memory leak

char* stringRev(char *s)
{	
	char* tmp;
	tmp = new char; //¿how many characters do you need?
	int i, cnt(0);
	for( ; ; )
	{
		cout <<  s[i] << endl; //¿why are you doing output here?
		cnt++;
	}
	for( ; ; )
	{
		tmp[] = s[   - - ];
	}
	tmp[i]='\0';
	return tmp;
}
Jan 30, 2020 at 3:55pm
Hint: no need to create a new string or mess with char arrays[].

Hint 2: how many swaps are needed to fully exchange every pair of characters?
Jan 30, 2020 at 4:08pm


This may be wrong, might not even compile (probably wont)

But this was my take (done in a phone so go easy on me). But you ain't never gonna learn getting answers off a forum like this

[Code]

#include <iostream>
using namespace std;
void stringRev(char *s);

int main()
{
char str[]="Happy Day";
cout << stringRev(str);
system ("pause > 0");
return 0;
}

char* stringRev(char *s)
{
char* tmp;
tmp = new char;
int i, cnt;
for( i=0;s[i]!=’\0’;i++ ; )
{
cout << s[i] << endl;
cnt++;
}
for( i=0; i<cnt; i++)
{
tmp[i] = s[cnt-i];
}
tmp[i]='\0';
For(i=0;i<cnt;i++){

Cout<<”tmp[i] “<<tmp[i]<<” s[i] “<<s[i]<<endl;
}
return tmp;


}

[/code]

Idk why this looks like this....whatever

I just noticed that there maybe some dereferenceing that needs to happen to set and display the data. I'm not really that thoroughly schooled in pointers yet to really be able to tell.
Last edited on Jan 30, 2020 at 5:19pm
Jan 30, 2020 at 4:47pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <utility>
#include <iostream>

char* reverse_string(char* s, int sz)
{
  for (int beg = 0, end = sz - 1; beg < end; )
    std::swap(s[beg++], s[--end]);
  return s;
}

int main()
{
    char s[] = "Hello";
    std::cout << "reverse(" << s << ") = " << reverse_string(s, sizeof s) << '\n';  
}
Topic archived. No new replies allowed.