给定一个字符串str ,其中包含未正确安排的源代码(C / C++ / Java代码),任务是以正确的方式格式化该代码并打印结果。
例子:
Input: str = "#includeint main(){ cout << \"geeksforgeeks\" }"
Output:
#include
int main()
{
cout << "geeksforgeeks"
}
Input: str = "#includeint main() { int a, b, c; c=a+b; printf(\"%d\", c); return 0; }"
Output:
#include
int main()
{
int a, b, c;
c=a+b;
printf("%d", c);
return 0;
}
方法:检查各种条件,例如# , { , } , ( ) , < , > ,;并根据需要设置代码格式。如果不需要更改或无法格式化代码,请照原样打印代码。
下面是上述方法的实现:
C++
// CPP program to rearrange the given source code
#include
using namespace std;
// Function to rearrange the code
void rearrange(string str)
{
string replaced;
int Open_paren = 0, Open_Braces = 0;
int Lessrthan = 0, i = 0, j = 0;
do {
// Various Conditions For The Code
if (str[i] == '#' || str[i] == '<' || str[i] == '>'
|| str[i] == ';' || str[i] == '}' || str[i] == '{'
|| str[i] == '(' || str[i] == ')') {
// Check for opening braces
if (str[i] == '{')
Open_Braces++;
// Check for closing braces
if (str[i] == '}')
Open_Braces--;
// For less than symbol
if (str[i] == '<' && Open_paren == 0)
Lessrthan++;
// For greater than symbol
if (str[i] == '>' && Open_paren == 0)
Lessrthan--;
// For open parenthesis
if (str[i] == '(') {
Lessrthan = 0;
Open_paren++;
}
// For closing parenthesis
if (str[i] == ')')
Open_paren--;
if (Open_paren > 0) {
replaced += str[i];
}
else {
// Replace the plain code
// for closing parenthesis
if (str[i] == ')')
replaced += str[i];
// Replace the code for open and close braces
else if (str[i] == '{' || str[i] == '}') {
replaced += '\n';
replaced += str[i];
replaced += '\n';
}
else if (Lessrthan > 0)
replaced += str[i];
// Replace the code for # symbol
else if (str[i] == '#') {
replaced += '\n';
replaced += str[i];
}
else {
replaced += str[i];
replaced += '\n';
}
}
}
// If all conditions do not
// work then print the code as it is
else {
replaced += str[i];
}
i++;
} while (i < str.length());
replaced += '\0';
// Print formatted code
for (i = 0; i < replaced.length(); i++)
cout << replaced[i];
printf("\n");
}
// Driver Code
int main()
{
string str = "#includeint main()"
"{ int a, b, c; c=a+b; printf(\"%d\", c);"
" return 0; }";
// Function call
rearrange(str);
return 0;
}
输出:
#include
int main()
{
int a, b, c;
c=a+b;
printf("%d", c);
return 0;
}
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。