Open In App

Rearrange the given source code

Improve
Improve
Like Article
Like
Save
Share
Report

Given a string str which contains the source code (C/C++/Java code) which is not arranged in a proper way, the task is to format that code in a proper way and print the result. Examples:

Input: str = "#include<stdio.h>int main(){ cout << \"geeksforgeeks\" }"
Output:
#include<stdio.h>
int main()
{
 cout << "geeksforgeeks" 
}

Input: str = "#include<stdio.h>int main() { int a, b, c; c=a+b; printf(\"%d\", c); return 0; }"
Output:
#include<stdio.h>
int main() 
{
 int a, b, c;
 c=a+b;
 printf("%d", c);
 return 0;

}

Approach: Check various conditions like #, {, }, (, ), <, >, ; and format the code as required. If no changes are required or the code cannot be formatted then print the code as it is. Below is the implementation of the above approach: 

C++




// CPP program to rearrange the given source code
#include <bits/stdc++.h>
using namespace std;
 
// Function to rearrange the code
void rearrange(string str)
{
    string replaced;
 
    int Open_paren = 0, Open_Braces = 0;
    int Lesserthan = 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)
                Lesserthan++;
 
            // For greater than symbol
            if (str[i] == '>' && Open_paren == 0)
                Lesserthan--;
 
            // For open parenthesis
            if (str[i] == '(') {
                Lesserthan = 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 (Lesserthan > 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 = "#include<stdio.h>int main()"
                 "{ int a, b, c; c=a+b; printf(\"%d\", c);"
                 " return 0; }";
 
    // Function call
    rearrange(str);
 
    return 0;
}


Java




/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.*;
// Java program to rearrange the given source code
 
public class Main {
     
    // Function to rearrange the code
    public static void rearrange(char[] str)
    {
        String replaced = "";
 
        int Open_paren = 0, Open_Braces = 0;
        int Lesserthan = 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)
                    Lesserthan++;
 
                // For greater than symbol
                if (str[i] == '>' && Open_paren == 0)
                    Lesserthan--;
 
                // For open parenthesis
                if (str[i] == '(') {
                    Lesserthan = 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 (Lesserthan > 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++)
            System.out.print(replaced.charAt(i));
        System.out.println("\n");
    }
     
    public static void main(String[] args) {
        String str = "#include<stdio.h>int main() { int a, b, c; c=a+b; printf(\"%d\", c); return 0; }";
 
        // Function call
        rearrange(str.toCharArray());
    }
}
 
// The code is contributed by Arushi Jindal.


Python3




# Python program to rearrange the given source code
 
# Function to rearrange the code
def rearrange(str):
    replaced = ""
 
    Open_paren = 0
    Open_Braces = 0
    Lesserthan = 0
    i = 0
    j = 0
 
    while i < len(str):
 
        # Various Conditions For The Code
        if str[i] == '#' or str[i] == '<' or str[i] == '>' or str[i] == ';' or str[i] == '}' or str[i] == '{' or str[i] == '(' or str[i] == ')':
 
            # Check for opening braces
            if str[i] == '{':
                Open_Braces += 1
 
            # Check for closing braces
            if str[i] == '}':
                Open_Braces -= 1
 
            # For less than symbol
            if str[i] == '<' and Open_paren == 0:
                Lesserthan += 1
 
            # For greater than symbol
            if str[i] == '>' and Open_paren == 0:
                Lesserthan -= 1
 
            # For open parenthesis
            if str[i] == '(':
                Lesserthan = 0
                Open_paren += 1
 
            # For closing parenthesis
            if str[i] == ')':
                Open_paren -= 1
 
            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
                elif str[i] == '{' or str[i] == '}':
                    replaced += '\n'
                    replaced += str[i]
                    replaced += '\n'
                elif Lesserthan > 0:
                    replaced += str[i]
 
                # Replace the code for # symbol
                elif str[i] == '#':
                    replaced += '\n'
                    replaced += str[i]
                else:
                    replaced += str[i]
                    replaced += '\n'
        else:
            # If all conditions do not
            # work then print the code as it is
            replaced += str[i]
 
        i += 1
 
    replaced += '\0'
 
    # Print formatted code
    for i in range(len(replaced)):
        print(replaced[i], end='')
    print("\n")
 
str = "#include<stdio.h>int main() { int a, b, c; c=a+b; printf(\"%d\", c); return 0; }"
 
# Function call
rearrange(list(str))
 
# This code is contributed by shivamsharma215


C#




using System;
 
// C# program to rearrange the given source code
public class MainClass {
    // Function to rearrange the code
    public static void rearrange(char[] str) {
        string replaced = "";
 
        int Open_paren = 0, Open_Braces = 0;
        int Lesserthan = 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)
                    Lesserthan++;
 
                // For greater than symbol
                if (str[i] == '>' && Open_paren == 0)
                    Lesserthan--;
 
                // For open parenthesis
                if (str[i] == '(') {
                    Lesserthan = 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 (Lesserthan > 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++)
            Console.Write(replaced[i]);
        Console.WriteLine("\n");
    }
 
    public static void Main(string[] args) {
        string str = "#include<stdio.h>int main() { int a, b, c; c=a+b; printf(\"%d\", c); return 0; }";
 
        // Function call
        rearrange(str.ToCharArray());
    }
}


Javascript




// Function to rearrange the code
function rearrange(str) {
    let replaced = "";
 
    let Open_paren = 0;
    let Open_Braces = 0;
    let Lesserthan = 0;
    let i = 0;
    let j = 0;
 
    while (i < str.length) {
 
        // 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 += 1;
            }
 
            // Check for closing braces
            if (str[i] === '}') {
                Open_Braces -= 1;
            }
 
            // For less than symbol
            if (str[i] === '<' && Open_paren === 0) {
                Lesserthan += 1;
            }
 
            // For greater than symbol
            if (str[i] === '>' && Open_paren === 0) {
                Lesserthan -= 1;
            }
 
            // For open parenthesis
            if (str[i] === '(') {
                Lesserthan = 0;
                Open_paren += 1;
            }
 
            // For closing parenthesis
            if (str[i] === ')') {
                Open_paren -= 1;
            }
 
            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 (Lesserthan > 0) {
                    replaced += str[i];
                }
 
                // Replace the code for # symbol
                else if (str[i] === '#') {
                    replaced += '\n';
                    replaced += str[i];
                } else {
                    replaced += str[i];
                    replaced += '\n';
                }
            }
        } else {
            // If all conditions do not
            // work then print the code as it is
            replaced += str[i];
        }
 
        i += 1;
    }
 
    replaced += '\0';
 
    // Print formatted code
    for (let i = 0; i < replaced.length; i++) {
        process.stdout.write(replaced[i]);
    }
    console.log();
}
 
let str = "#include<stdio.h>int main() { int a, b, c; c=a+b; printf(\"%d\", c); return 0; }";
 
// Function call
rearrange(str.split(""));


Output:

#include<stdio.h>
int main()
{
 int a, b, c;
 c=a+b;
 printf("%d", c);
 return 0;
 
}


Last Updated : 02 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads