+ 1
Is there any way to write this code in c++ with ONLY one loop??(without using any header file for help)
This is kind of challenge our teacher told us to do and this is the question: Write a program which takes one string and if there is consecutive spaces deletes the extra spaces
2 Answers
+ 2
Yes, you can do! 👍
https://code.sololearn.com/cZfyaSiqgqsO/#cpp
+ 1
I do not know c++, but in JS it will look like this:
function f(str){
for (let i=0;i<str.length;i++){
if (str.charAt(i)==str.charAt(i+1) && str.charAt(i)==" "){
str=str.slice(0,i+1)+str.slice(i+2);
i--;
}
}
return str;
}
in the loop, we compare the i-th symbol with the (i + 1) symbol, and if they are equal to each other and equal to " ", then we delete the (i + 1) symbol.
https://code.sololearn.com/WYF1ZI7sTwd4/?ref=app