2019년 4월 13일 토요일

# 단어 단위로 뒤집기 ( 한글 제외 )

 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
using namespace std;

void Solution(char* dst, int descSize, const char* src);
int GetLength(const char* string);

int main() {
 char src[] = "hello world this is test";         
 char dst[512];
 Solution(dst, sizeof(dst), src);
}

void Solution(char* dst, int descSize, const char* src) {
 int srcLength = GetLength(src);
 if (srcLength >= descSize) {
  // buffer overflow
  return;
 }
 int writePos = 0;
 int wordEndPos = srcLength - 1;
 for (int reverseIdx = srcLength - 1; reverseIdx >= 0; reverseIdx--) {
  if (src[reverseIdx] == ' ') {
   dst[writePos] = ' ';
   writePos++;
   wordEndPos = reverseIdx - 1;
  }else {
   // scanning word.
   while ((src[reverseIdx - 1] != ' ') && (reverseIdx != 0)) {reverseIdx--;}
   // copy source string to destination string.
   for (int readPos = reverseIdx; readPos <= wordEndPos; readPos++) {
    dst[writePos] = src[readPos];
    writePos++;
   }
   wordEndPos = reverseIdx - 1;
  }
 }
 dst[writePos] = '\0';
}

// return length of string without null terminator.
int GetLength(const char* charSequence) {
 int idx = 0;
 while (charSequence[idx] != '\0') { idx++;}
 return idx;
}

댓글 없음:

댓글 쓰기