Following is the code for replacing all the spaces in a string (alternately you can also have any other string or character that you can replace.
Or simply use the replace method of String class for completing this operation.
public class ReplaceAllSpaces {
/**
* @param args
*/
static String replacement = "%20";
public static void main(String[] args) {
System.out
.println(replaceAllSpaces_Using_String("adasvasv adfa adfa adfasdf dfash he j f ss sfdsgf s sdfg sfgsfgs s gsdf sdfgsdfgsgdfs s"));
System.out
.println(replaceAllSpaces_using_StringBuilder("adasvasv adfa adfa adfasdf dfash he j f ss sfdsgf s sdfg sfgsfgs s gsdf sdfgsdfgsgdfs s"));
System.out
.println(replaceAllSpaces("adasvasv adfa adfa adfasdf dfash he j f ss sfdsgf s sdfg sfgsfgs s gsdf sdfgsdfgsgdfs s"));
System.out.println(new Integer(new String(" ").charAt(0)));
}
/**
* Completes the algo in O(n) time where n is the spaces in the string.
* However the space complexity is Triple the size of string used in both
* the cases
*
* @param string
* @return
*/
private static String replaceAllSpaces_Using_String(String string) {
String[] stra = string.split(" ");
string = stra[0] + replacement;
for (int i = 1; i < stra.length-1; i++) {
string = string + stra[i] + replacement;
}
string = string +stra[stra.length-1];
return string;
}
private static StringBuilder replaceAllSpaces_using_StringBuilder(
String string) {
String[] stra = string.split(" ");
StringBuilder strt = new StringBuilder(stra[0] + replacement);
for (int i = 1; i < stra.length-1; i++) {
strt = strt.append(stra[i] + replacement);
}
strt = strt.append(stra[stra.length-1]);
return strt;
}
/**
* Completed the algo in O(2n) if we dont use the easy builds
*
* In Java as the size of the
* any array can not be changed (either increased or decreased )=> in that
* case we will have to use up another array or size length + spacecount *
* replacemant.length so either we will have a space complexity of
* 2(length)+ spacecount * replacement.length or the O(3length) in worst
* case.
*/
public static char[] replaceAllSpaces(String str) {
int spacecount = 0;
char[] ch = str.toCharArray();
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 32)
spacecount++;
}
int newlength = str.length() + spacecount * 2;
// ch[newlength-1] = '\0'; --> not possible
char[] chn = new char[str.length() + spacecount * 2];
for (int i = ch.length - 1; i >= 0; i--) {
if (ch[i] == ' ') {
chn[newlength - 1] = '0';
chn[newlength - 2] = '2';
chn[newlength - 3] = '%';
newlength = newlength - 3;
} else {
chn[newlength - 1] = ch[i];
newlength--;
}
}
System.out.println(chn);
return chn;
}
}
No comments:
Post a Comment