Reverse The Words In A Sentence But Not The Letters [duplicate] - javascript

This question already has answers here:
Reversing a string
(4 answers)
Closed 5 years ago.
I want to make a program to reverse the words only, not the letters.
For example...
i love india
... should become...
india love i
Another example...
google is the best website
... should become...
website best the is google
With spaces I have thoroughly researched on it but found just nothing.
My logic is that I should just give you my program that is not working. If you find a small error in my code please give the solution for it and a corrected copy of my program. Also, if you are not too busy, can you please give me the logic in a flow chart.
my logic is here
Thank you for your time.

class Solution {
public String reverseWords(String s) {
if (s == null || s.length() == 0) {
return "";
}
// split to words by space
String[] arr = s.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = arr.length - 1; i >= 0; --i) {
if (!arr[i].equals("")) {
sb.append(arr[i]).append(" ");
}
}
return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
}
}

1.
Store the words of each line in a string array.
2.
Print the elements of the array from the last item to the first.

Related

Javascript - Online Coding assessment to mask credit cards numbers with # [duplicate]

This question already has answers here:
Masking credit card number
(5 answers)
Closed 12 months ago.
I got the below coding assessment question in Javascript. I tried my best to solve but there are few edge cases I missed. I need help to identify those missing cases
Usually when you buy something, you're asked whether your credit card number, phone number or answer to your most secret question is still correct.
However, since someone could look over your shoulder, you don't want that shown on your screen. Instead, we mask it.
This is what I tried so far
function maskify (cc) {
if (cc.length < 6) {
let reversed = reverse(cc);
let newString = '';
for (let i = 0; i < reversed.length; i++) {
if (i < 4) {
newString += reversed[i];
} else {
newString += '#';
}
}
return reverse(newString);
Output
This is my solution:
function maskify (cc) {
// If less than 6 characters return full number
if (cc.length < 6)
return cc;
// Take out first character
let firstChar = cc.charAt(0);
cc = cc.slice(1);
// Replace characters except last 4
cc = cc.replace(/\d(?=.{4,}$)/g, '#');
// Add first character back
cc = firstChar + cc;
return cc;
}
// Run every example number
const tests = ["4556364607935616", "4556-3646-0793-5616",
"64607935616", "ABCD-EFGH-IJKLM-NOPQ",
"A1234567BCDEFG89HI", "12345", "", "Skippy"];
tests.forEach((number) => console.log(`Testing: ${number} - Output: ${maskify(number)}`));
I ran it with all the numbers of your example and it gets the correct output.

How to replace a specific part from strings in odd and even index in JavaScript? [duplicate]

This question already has answers here:
Matching quote wrapped strings in javascript with regex
(3 answers)
Closed 2 years ago.
How to replace a specific part from strings in odd and even index in JavaScript?
I want to replace the 1, 3, 5, etc ``` with <span class="styles"> and the 2, 4, 6, etc ``` with </span>. So that I can style the areas.
It is somewhat similar to the Stack Overflow 's Textarea/answer&question area or GitHub's editor.
For example, I have a string:
const str = "Almost ```before``` we knew it, ```we``` had left the ```ground```.";
When I will print it on the page, I want it somewhat like this.
Almost <span class="styles">before</span> we knew it, <span class="styles">we</span> had left the <span class="styles">ground</span>.
I have researched a lot but I am only able to extract this ``` from the string and I don't know how to replace in odd and even pattern.
Any help would be appreciated.
You could search for a group between the separators with non greedy search between and take the group with new tags around.
const
string = "Almost ```before``` we knew it, ```we``` had left the ```ground```.",
result = string.replace(/```(.*?)```/g, '<span class="styles">$1</span>');
console.log(result);
You could iterate through each one and do something along the lines as the following:
const str = "Almost ```before``` we knew it, ```we``` had left the ```ground```.";
const parts = str.split('```')
let final = parts[0]
for (let i = 1; i < parts.length -1; i++) {
if (i % 2 === 1) {
final += '<span class="styles">'
} else {
final += '</span>'
}
final += parts[i]
}
final += '</span>' + parts[parts.length - 1]
function repl(str, mark) {
var inside = false
var last = 0
var builder = []
for(var i in str) {
i = parseInt(i)
if (str.substring(i, i + mark.length) == mark) {
builder.push(str.substring(last, i))
last = i + mark.length
if (inside) {
builder.push(`<span class="stile">`)
} else {
builder.push(`</span>`)
}
inside = !inside
}
}
builder.push(str.substring(last))
return builder.join("")
}

easy way to multiply a value to successive substrings in javascript

Good morning, sorry for my poor English.
I'm a neophyte and I'm trying to create a javascript program that, given a string in input, if it finds inside defined substrings it returns a value to each substring and returns the sum of the values ​​found as output. Everything ok here. But I'm finding it difficult to manage the case where in front of the substring that I'm looking for, there's for example "2x" which means that the value of the next substring (or of all subsequent substring) is to be multiplied for 2. How can I write in simple code this exception?
Example:
A1 = 1
M1 = 1
input description = A1-M1
output = 2
input descritpion = 2 x A1-M1
output = 4
Thanks in advance
For more comprehesion, you can find my code below:
let str_description = "2 x A1-M1";
var time_mont = [];
var time_cloa = [];
if(str_description.includes("A1")){
time_mont.push (0.62);
} else {
time_mont.push (0);
}
if(str_description.includes("M1")){
time_mont.push (0.6);
} else {
time_mont.push (0);
}
How can I manage "2 x " subtring?

Adding space to fill array length

I am working with a javascript program that needs to be formatted a certain way. Basically, I need to have each section of information from an array be a set length, for example 12 characters long, and no more than that.
The problem I am running into comes when a value in the array is NOT 12 characters long. If I have a value that is less than the 12 characters the remaining character allotment needs to be filled with blank spaces.
The length of each section of information varies in size and is not always 12. How can I add X number of blank spaces, should the length not meet the maximum requirement, for each section?
This is where I am at with adding space:
str = str + new Array(str.length).join(' ');
I am pretty sure what I have above is wrong but I believe I am on the right track with the .join function. Any ideas?
EDIT: I was asked to show a wanted outcome. It is a bit complicated because this javascript is being run out of a web report tool and not out of something like Visual Studio so its not traditional JS.
The outcome expected should look something like:
Sample Image
So as shown above the data is in one line, cutting off longer strings of information or filling in blank spaces if its too short for the "column" to keep that nice even look.
try this code and leverage the wonders of the map function:
let say your array is:
var myArr = ["123456789012", "12345678901", "123"];
now just apply this function
myArr.map(function(item){ //evalueate each item inside the array
var strLength = item.length; //apply this function to each item
if (strLength < 12){
return item + ' '.repeat(12-item.length) //add the extra spaces as needed
} else {
return item; // return the item because it's length is 12 or +
}
})
What you are looking for is the ' '.repeat(x) - where x is the times you want to repeat the string you have set, it could be '*'.repeat(2) and you would get '**', if you want to understand more about it look at the docs
depending on which version of javascript, this might work:
if (str.length < 12) str += ' '.repeat(12 - str.length);
Not exactly sure how you're setup -- but something like the following will accept an array and return another array with all its values being 12 characters in length.
var array = ['Test', 'Testing', 'Tested', 'This is not a Test'];
var adjustedArray = correctLength(array, 12);
function correctLength(array, length) {
array.map(function(v, i) {
if (array[i].length < length) {
array[i] += Array((length+1) - array[i].length).join('_');
}
// might not need this if values are already no greater than 12
array[i] = array[i].substring(0, length);
});
return array;
}
console.log(adjustedArray);

Reverse a String in JS [duplicate]

This question already has answers here:
How do you reverse a string in-place in JavaScript?
(57 answers)
Closed 7 years ago.
I'm going through tutorials to code (I'm fairly new at this), and this particular exercise is racking my brain. Here are the parameters:
Reverse the provided string.
You may need to turn the string into an array before you can reverse it. Your result must be a string.
and here is the code I'm given to start with:
function reverseString(str) {
return str;
}
reverseString('hello');
expect(reverseString('hello')).to.be.a('String');
expect(reverseString('hello')).to.equal('olleh');expected 'hello' to equal 'olleh'
expect(reverseString('Howdy')).to.equal('ydwoH');expected 'Howdy' to equal 'ydwoH'
expect(reverseString('Greetings from Earth')).to.equal('htraE morf sgniteerG');expected 'Greetings from Earth' to equal 'htraE morf sgniteerG'
Any suggestions out there on how to accomplish this?
** Edit: I figured out what my issue was. The particular IDE of the tutorial site made it confusing. Apparently I was meant to hit one of the objectives listed (not all of them in one script as I previously thought). This was accomplished by return str.split( '' ).reverse( ).join( '' );. The parameters for the split and join methods were a little confusing at first as well. Most online tutorials of this method use splitting words as an example, so I didn't realize going from
" " to ""
would change the process from reversing words to reversing letters.
Arrays have a method called reverse( ). The tutorial is hinting at using this.
To convert a string into an array of characters (in reality they're just single character strings), you can use the method split( ) with an empty string as the delimiter.
In order to convert the array back into a string, you can use the method join( ) again, with an empty string as the argument.
Using these concepts, you'll find a common solution to reversing a string.
function reverseString(str) {
return str.split( '' ).reverse( ).join( '' );
}
Pretty manual way to accomplish this
var j = 'abcdefgh';
var k = j.split('');
var reversedArr = []
for(var i = k.length; i >= 0; i--) {
reversedArr.push(k[i])
}
var reversedStr = reversedArr.join('')
console.log(reversedStr)
You can read more here: http://eddmann.com/posts/ten-ways-to-reverse-a-string-in-javascript/
function reverse(s) {
var o = '';
for (var i = s.length - 1; i >= 0; i--)
o += s[i];
return o;
}
A string is an array of characters, so you can use the reverse function on the array to reverse it and then return it:
function reverseString(str) {
return str.split('').reverse().join('');
}
var reversedStr = normalStr.split("").reverse().join("");

Categories

Resources