/*コメント*/を取り除く
Posted feedbacks - C++
std::stringで。
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 | #include <iostream>
#include <string>
std::string remove_comment(const std::string& s)
{
std::string ret;
std::string::size_type i1 = 0;
while (1)
{
std::string::size_type i2;
if ((i2 = s.find("/*", i1)) == std::string::npos)
{
ret.append(s.substr(i1));
break;
}
else
{
ret.append(s.substr(i1, i2 - i1));
i1 = i2 + 2;
}
if ((i2 = s.find("*/", i1)) == std::string::npos)
{
break;
}
else
{
i1 = i2 + 2;
}
}
return ret;
}
void run(const std::string& s)
{
std::cout << remove_comment(s) << std::endl;
}
int main()
{
run("AAA");
run("AAA/*BBB*/");
run("AAA/*BBB");
run("AAA/*BBB*/CCC");
run("AAA/*BBB/*CCC*/DDD*/EEE");
run("AAA/a//*BB*B**/CCC");
}
|
<algorithm>のstd::searchを使ってみた。size_typeよりイテレータのほうが扱いやすいかと思ったけど、そうでもなかった。(bcc32で確認)
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 | #include <iostream>
#include <string>
#include <algorithm>
std::string remove_comment(const std::string& s)
{
std::string ret;
const std::string beg = "/*";
const std::string end = "*/";
std::string::const_iterator it1 = s.begin();
while (1)
{
std::string::const_iterator it2;
it2 = std::search(it1, s.end(), beg.begin(), beg.end());
ret.append(std::string(it1, it2));
if (it2 == s.end())
{
break;
}
else
{
it1 = it2 + beg.size();
}
it2 = std::search(it1, s.end(), end.begin(), end.end());
if (it2 == s.end())
{
break;
}
else
{
it1 = it2 + end.size();
}
}
return ret;
}
void run(const std::string& s)
{
std::cout << remove_comment(s) << std::endl;
}
int main()
{
run("AAA");
run("AAA/*BBB*/");
run("AAA/*BBB");
run("AAA/*BBB*/CCC");
run("AAA/*BBB/*CCC*/DDD*/EEE");
run("AAA/a//*BB*B**/CCC");
}
|

にしお
#3373()
Rating0/0=0.00
なお、「/*」と入力末尾で挟まれた部分も取り除いてください。 つまり、入力が「AAA/*BBB」なら出力は「AAA」です。 また、コメントは入れ子になりません。入力が「AAA/*BBB/*CCC*/DDD*/EEE」のとき、ひとつめの「*/」でコメントが終わるので出力は「AAADDD*/EEE」になります。 「//」や「**」が混ざる場合の挙動は失敗しやすいので要注意です。
Pythonでの実行例は下のようになります:
>>> remove_comment('AAA') 'AAA' >>> remove_comment('AAA/*BBB*/') 'AAA' >>> remove_comment('AAA/*BBB') 'AAA' >>> remove_comment('AAA/*BBB*/CCC') 'AAACCC' >>> remove_comment('AAA/*BBB/*CCC*/DDD*/EEE') 'AAADDD*/EEE' >>> remove_comment('AAA/a//*BB*B**/CCC') 'AAA/a/CCC'このお題は匿名での投稿を参考にして作成しました。 ありがとうございます。
[ reply ]