Cod sursa(job #1343242)

Utilizator raduneagoeNeagoe Radu raduneagoe Data 15 februarie 2015 01:13:41
Problema Convertor Scor 70
Compilator java Status done
Runda rosedu_cdl_2015 Marime 2.21 kb
import java.io.*;
import java.util.Scanner;

public class Main
{
	public static int charAppears(String s, char ch)
	{
		int counter = 0;
		for(int i = 0; i < s.length(); i++)
		{
			if(s.charAt(i) == ch)
				counter++;
		}
		s = null;
		return counter;
	}
	
	public static CharSequence deleteChar(CharSequence str)
	{	
		while(str.charAt(0) == ' ' || str.charAt(0) == '"' || str.charAt(str.length() - 1) == ' ' || str.charAt(str.length() - 1) == '"' || str.charAt(str.length() - 1) == '}' || str.charAt(str.length() - 1) == ',')
		{
			if(str.charAt(0) == ' ' || str.charAt(0) == '"')
				str = str.subSequence(1,str.length());

			if(str.charAt(str.length() - 1) == ' ' || str.charAt(str.length() - 1) == '"' || str.charAt(str.length() - 1) == '}' || str.charAt(str.length() - 1) == ',')
				str = str.subSequence(0,str.length() - 1);
		}
		return str;
	}
	
	public static void main(String[] args) throws IOException
	{
		CharSequence JSON = new Scanner(new FileInputStream("convertor.in")).useDelimiter("\\Z").next().replaceAll("(\\r|\\n)", "");
		PrintWriter writer = new PrintWriter("convertor.out");
		
		// prima linie
		int a = ((String) JSON).indexOf("\"") + 1, b = ((String) JSON).indexOf(":") - 1;
		int m = charAppears(((String) JSON).substring(((String) JSON).indexOf(":"), ((String) JSON).indexOf("}")), ',') + 1; //nr virgulelor = nr coloanelor
		int n = charAppears(JSON.toString(), '}'); //nr '}' = nr liniilor, fara prima linie
		
		for (int i = 0; i < m; i++)
		{
			writer.print(deleteChar(JSON.subSequence(a, b)) + ",");
			
			a = ((String) JSON).indexOf(",", a) + 1;
			b = ((String) JSON).indexOf(":", b + 2) - 1;
		}
		
		//urmatoarele linii
		a = b = 0;
		for(int i = 0; i < n; i++)
		{
			writer.println();
			
			for(int j = 0; j < m; j++)
			{
				a = ((String) JSON).indexOf(":", a) + 1;
				b = ((String) JSON).indexOf(",", b) + 1;
				try //pe ultima linie nu voi mai avea "}," si va da eroare
				{
					writer.print(deleteChar(JSON.subSequence(a, b)) + ",");
				} 
				catch (StringIndexOutOfBoundsException e)
				{
					b = ((String) JSON).lastIndexOf("}");
					writer.print(deleteChar(JSON.subSequence(a, b)) + ",");
				}
			}
		}
		writer.close();
	}
}