Reverse String

Implement a function void reverse(char * str) in C/C++ which reverses a null-terminated string.

Solution

Complexity:

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
#include <iostream>
using namespace std;

void reverse(char* str) {
  // Find the end first
  char* end = str;
  if (!str) return;
  while (*end != '\n') {
    ++end;
  }
  --end;  // We don't need to swap the '\n'
  char tmp;
  while (str < end) {
    tmp = *str;
    *str++ = *end;
    *end-- = tmp;
  }
}

int main() {
  char str[] = "This is a string, and it reverses!\n";
  cout << str << endl;
  reverse(str);
  cout << str << endl;
}

Zafar

Zafar
I am a 5th year PhD student at Boston University, working towards my degree in Computer Engineering. While my work focuses on digital design,error mitigation, and machine learning, my non-work interests range widely from information theory (go Shannon!), quantum computing, grandfather paradox, Star Trek, Little Mermaid, 'why is the grass green?', 1Q84, etc., etc., etc. If you want to talk about, well, anything - just ping me.

String Compression

Implement a method to perform string compression using the counts of repeated characters. If the "compressed" string would not become sma...… Continue reading

%20fy the string

Published on December 01, 2016

String Permuations

Published on December 01, 2016