Below are some simple programming problems and several approaches to each. To see the code for an approach, click its "See Code" button.
"this is a sentence, reverse the word order" will have the reverse order of: "order word the reverse sentence, a is this"
Enter a string to be reversed:
//Problem #1, Approach One
//Tom Susic, tsusic.home.att.net
String.prototype.reverseA1 = function () {
var str = this.toString(),
result = "",
word = "";
for (var i = 0; i < str.length; i++) {
if (str.charAt(i) == " ") {
result = " " + word + result;
word = "";
} else {
word = word + str.charAt(i);
}
}
result = word + result; //pick up any last word
return result;
};
//Problem #1, Approach Two
//Tom Susic, tsusic.home.att.net
String.prototype.reverseA2 = function () {
var str = this.toString(),
i = 0,
endCharCount = 0,
word = "";
for (var c = 0; c < str.length; c++) {
if (str.charAt(i) == " ") {
str = str.substring(i + 1, str.length - endCharCount) +
" " + word +
str.substring(str.length - endCharCount);
endCharCount = endCharCount + i + 1;
word = "";
i = 0;
} else {
word = word + str.charAt(i++);
};
};
return str;
};
//Problem #1, Approach Three
//Tom Susic, tsusic.home.att.net
//This doesn't work because strings are immutable.
String.prototype.reverseA3 = function () {
var str = this.toString(),
strEnd = str.length,
start = 0,
chrEnd = 0,
tempChr = "";
for (var c = 0; c < str.length; c++) { //swap string characters
if (c < --strEnd) {
tempChr = str.charAt(c);
str.charAt(c) = str.charAt(strEnd);
str.charAt(strEnd) = tempChr;
}
if (str.charAt(c) == " ") { //swap word characters
chrEnd = c;
for (var i = start; i < --chrEnd; i++) {
tempChr = str.charAt(i);
str.charAt(i) = str.charAt(chrEnd);
str.charAt(chrEnd) = tempChr;
}
start = c + 1;
}
}
return str;
};