-
Notifications
You must be signed in to change notification settings - Fork 160
/
Remove comments.cpp
75 lines (48 loc) · 1.6 KB
/
Remove comments.cpp
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
Remove the comments in a string, comments are the chars after "//" or between "//* * //"
*/
#include<iostream>
using namespace std;
const char* RemoveComment(const char* org, char str[]) {
if (org == NULL || str == NULL) return strN;
const char* iter = org;
char* writer = str;
char* start = NULL;
while (*iter != '\0') {
if (*iter == '/') {
if (*(iter+1) == '/') {
while (*iter != '\n' && *iter !='\0') { //omit all rest chars
iter++;
}
continue;
} else if (*(iter + 1) == '*') {
if (start == NULL) {
start = writer; //record the previous position before /*
}
*writer++ = *iter++;
*writer++ = *iter++;
continue;
}
} else if (*iter == '*') {
if (*(iter+1) == '/') {
if (start != NULL) {
writer = start; //jump back to the previous char of /*
start = NULL;
iter += 2; //omit */
continue;
}
}
}
*writer++ = *iter++;
}
*writer = '\0';
return str;
}
int main() {
const char text[] = "fsdf /*teert */ afdsaf";
char res[] = "";
char *p = res;
RemoveComment(text, p);
cout<<res<<endl;
return 0;
}