How to split String in words and populate an array

Here a simply method to split a string in words and generate an array.
In this case I use a Length param to limit substring size.

 


...

public static String[] splitStringInWordsAndCreateArrayWithLineInSize(String input,Integer lineLength){
		String[] words = input.split(" ");
 		List<String> list = new ArrayList<String>();
 		StringBuilder line = new StringBuilder();
 		for (int x = 0; x < words.length; x++) {
 			
 			
 			Boolean c = ((line.toString()+words[x]+" ").length()<lineLength);
 			if(c){
 				line.append(words[x]).append(" ");
 			}else{
 				list.add(line.toString());
 				line = new StringBuilder(words[x]).append(" ");
 			}
 		}
 		if(line.toString().length()>0){
 			list.add(line.toString());	
 		}
 		
 		Object[] arrObj = list.toArray();
 		String[] arrString = Arrays.copyOf(arrObj, arrObj.length, String[].class);
 		
		return arrString;
	}

...

And here unit test:


...

@Test
	 	public void testSplitStringInWordsAndCreateArrayWithLineInSize(){
	 		String s = "Prodotti tricologici per la cura e la bellezza dei capelli,quali shampoo, lozioni per capelli, preparati per ondulare icapelli, preparati per effettuare la permanente dei capelli,tinture per capelli, gel per capelli, lacche e fissatori percapelli,preparati per ravvivare il colore dei capelli . ";
	 		Integer lineLength = 62;
	 		String[] out = FYStringUtils.splitStringInWordsAndCreateArrayWithLineInSize(s, lineLength);
	 		StringBuilder rebuild = new StringBuilder();
	 		for(int x=0;x<out.length;x++){
	 			//System.out.println("x-"+out[x]);
	 			assertThat(out.length<lineLength).isTrue();
	 			rebuild.append(out[x]);
	 		}
	 		
	 		
	 		assertThat(rebuild.toString()).isEqualTo(s);
	 		
	 	}

...

Leave a Reply

Your email address will not be published. Required fields are marked *

Antispam Question * Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.