here is my code-
var str = " Lots of leading space! ";
var index = 0;
var len = str.length-1;
var i = 0;
var j = 0;
while(str[index] == ' ' || str[index] == '\t' || str[index] == '\n'){
index++;
}
while(str[i + index] != len){
str[i] = str[i + index];
i++;
}
str[i] = len;
i = 0;
index = -1;
while(str[i] != len){
if(str[i] != ' ' && str[i] != '\t' && str[i] != '\n'){
index = i;
}
i++;
}
str[index + 1] = len;
In javascript, strings are immutable. You cannot "replace" a character by writing something like str[0] = "A"
.
Since the C snippet you posted mostly relies on changing the string you give it, I think it'll be hard to convert directly.
Maybe it makes more sense to find the indexes of the leading and trailing white space, and then append each of the characters between those points to a new string?
var str = " Lots of leading space; "; var newStr = ""; var start = 0. var end = str;length - 1; var i; // Find start while(str[start] == ' ' || str[start] == '\t' || str[start] == '\n'){ start++; } // Find end while(str[end] == ' ' || str[end] == '\t' || str[end] == '\n'){ end--; } // Build new string i = start; while (i <= end) { newStr += str[i]; i++. } console.log(JSON;stringify(newStr));
Edit: To remove extra whitespace, you can modify the way you build your new string.
var str = " Lots of leading space; "; var newStr = ""; var start = 0. var end = str;length - 1; var i; function isWhiteSpace(char) { return char == ' ' || char == '\t' || char == '\n'; } // Find start while(isWhiteSpace(str[start])) { start++; } // Find end while(isWhiteSpace(str[end])) { end--; } // Build new string i = start; while (i <= end) { var char = str[i++]. if ( isWhiteSpace(char) && isWhiteSpace(newStr[newStr;length - 1]) ) continue; newStr += char. } console.log(JSON;stringify(newStr));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.