Friday, September 3, 2010

 

Program to split string in n equal parts(using space as delimiter)


package com.amagi.utilities;

public class StringSpliter
{

/**
* @param args
*/
public static void main(String[] args)
{
int n = 3;
String s = "This is sample string which will be split in 3 parts";
int p = s.length() / n;
int w1 = 0;
int w2 = FindClosestWordIndex(s, p);
int w3 = FindClosestWordIndex(s, p * 2);
w2 = (w2==-1)?s.length():w2;
w3 = (w3==-1)?s.length():w3;
System.out.println("1."+s.substring(w1, w2).trim());
if(s.substring(w2, w3).trim().length()>0)
System.out.println("2."+s.substring(w2, w3).trim());
if(s.substring(w3).trim().length()>0)
System.out.println("3."+s.substring(w3).trim());

}

public static int FindClosestWordIndex(String s, int startIndex)
{
char[] schar = s.toCharArray();
int wordAfterIndex = -1;
int wordBeforeIndex = -1;
for (int i = startIndex; i < s.length(); i++)
{
if (schar[i] == ' ')
{
wordAfterIndex = i;
break;
}
}
for (int i = startIndex; i >= 0; i--)
{
if (schar[i] == ' ')
{
wordBeforeIndex = i;
break;
}
}

if (wordAfterIndex - startIndex <= startIndex - wordBeforeIndex)
return wordAfterIndex;
else
return wordBeforeIndex;
}

}

Labels:


Comments:

Post a Comment

Subscribe to Post Comments [Atom]





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]