Jul 30

The following code will split the string into chunks, each of length ‘nchars’ (except potentially the last chunk)

int len = string.length();
for (int i=0; i<len; i+=nchars)
{
    String part = string.substring(i, Math.min(len, i + nchars)));
}

Another more exotic option uses regular expression and the spit() method. The number of dots in the regexp controls the length of each part.

// Splits string into 3 character long pieces.
String[] parts = string.split("(?<=\\G...)");

See how to fill a string with a character for how to dynamically generate a regexp for any number of characters. Though I’d probably go with the first method.

written by objects \\ tags: , , ,

Jul 28

Java 1.5 added a replace() method that could be used to replace all occurrences of a string wiuth another string

s = s.replace(" ", "");

Prior to 1.5 you can use a regular expression with the replaceAll() method to achieve that.

s = s.replaceAll(" ", "");

// Or to replace all whitespace

s = s.replaceAll("\\s", "");

Let us know if you need a different solution.

written by objects \\ tags: , ,

Jul 27

The Calendar class can be used to generate a simple calendar display.

private static void showMonth(Calendar cal) {
	int month = cal.get(Calendar.MONTH);
	int firstDayOfWeek = cal.getFirstDayOfWeek();
	
	// Display day names as headers
	
	cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
	for (int i=0; i<7; i++) {
		
		System.out.print(cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()));
		System.out.print(" ");
		cal.add(Calendar.DATE, 1);
	}
	System.out.println();
	
	// Display dates in month
	
	cal.set(Calendar.DATE, cal.getMinimum(Calendar.DATE));
	
	// Now display the dates, one week per line
	
	StringBuilder week = new StringBuilder();
	
	while (month==cal.get(Calendar.MONTH)) {
		
		// Display date
		
		week.append(String.format("%3d ", cal.get(Calendar.DATE)));
					
		// Increment date
		
		cal.add(Calendar.DATE, 1);

		// Check if week needs to be printed
		
		if (cal.get(Calendar.MONTH)!=month) {
			
			// end of month
			// just need to output the month
			
			System.out.println(week);
			
		} else if (cal.get(Calendar.DAY_OF_WEEK)==firstDayOfWeek) {
			
			// new week so print out the current week
			// first check if any padding needed
			
			int padding = 28-week.length();
			if (padding>0) {
				
				// pad out start of week
				
				week.insert(0, 
                                    String.format("%"+padding+"s", " "));
			}
			System.out.println(week);
			week.setLength(0);
		}
	}
}

written by objects \\ tags: , ,