Question d’entretien chez Amazon

Delete extra spaces in a string.

Réponses aux questions d'entretien

Utilisateur anonyme

21 oct. 2012

Java String removeSpaces(String s){ StringBuffer sb = new StringBuffer(); for(int index = 0; index < s.length(); index++){ if(!s.charAt(index) == ' '){ sb.append(s.charAt(index)+""); } } return sb.toString(); }

Utilisateur anonyme

24 mai 2012

This is pretty simple, i did this in couple of second yesterday, as I have requirement where i have to trim to string using Jscirpt check this code below I did three types of trim here Left_trim : removing whitespace from left Right _trim : removing whitespace from right and trim function to make call of above two methods I love using Regular expression so here are the concrete methods String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,""); } String.prototype.ltrim = function() { return this.replace(/^\s+/,""); } String.prototype.rtrim = function() { return this.replace(/\s+$/,""); } Here is the simple implementation function trim(stringToTrim) { return stringToTrim.replace(/^\s+|\s+$/g,""); } function ltrim(stringToTrim) { return stringToTrim.replace(/^\s+/,""); } function rtrim(stringToTrim) { return stringToTrim.replace(/\s+$/,""); } // example of using trim, ltrim, and rtrim var myString = " hello my name is "; alert("*"+trim(myString)+"*"); alert("*"+ltrim(myString)+"*"); alert("*"+rtrim(myString)+"*"); Now little more advance or i should say optimized implementation function ltrim(str) { for(var k = 0; k =0 && isWhitespace(str.charAt(j)) ; j--) ; return str.substring(0,j+1); } function trim(str) { return ltrim(rtrim(str)); } function isWhitespace(charToCheck) { var whitespaceChars = " \t\n\r\f"; return (whitespaceChars.indexOf(charToCheck) != -1); }