static String leadingSpacesToTabs(final String in) { StringBuilder sb = new StringBuilder(in); for (int i = 0; i < sb.length(); i++) { if (sb.charAt(i) != ' ') break; sb.setCharAt(i, '\t'); } return sb.toString(); } static void exampleUse() { final String spaceLine = " <div>"; System.out.println("before=" + spaceLine); final String tabLine = leadingSpacesToTabs(spaceLine); System.out.println(" after=" + tabLine); }
Programming Tips - Java: change leading spaces in a string to tabs
Date: 2019apr12
Language: Java
Level: beginner
Keywords: replace, replaceAll, regex
Q. Java: change leading spaces in a string to tabs
A. Here is a simple function that does that