I need a function that works like split
var string = "a|b|c"
console.log(string.split('|'))
to get a string and split it using loop
function splitstr(str, charToSplit){
}
I want the output of ('a|b|c', '|') to be ["a", "b", "c"]
Here is a slightly simpler solution that works correctly:
function splitStr(str, separator) {
const parts = [];
let nextPart = '';
for (let i = 0; i <= str.length; i++) {
if (str[i] === separator || i === str.length) {
parts[parts.length] = nextPart;
nextPart = '';
} else {
nextPart += str[i]
}
}
return parts;
}
console.log(splitStr("abc|abcd|ac", "|"));
You can use the code below.
This code had 8 steps to it.
Loops through the string
Checks if the current item is equal to charToSplit
If it is, it loops through the values in between startIndex and your current index (excluding your current index, which is the character you want to split on)
It first sets the value of output[currentIndex] to an empty string (since using += on something that doesn't exist doesn't work correctly
Then it adds the current letter you are on to output
startIndex is set to your current index + 1 (which is the character after the character that you want to split on)
currentIndex is increased by 1 since you're now on the next set of values
Finally, the code returns output
Note: The final extra loop after the first loop is there to add the last value to your output array.
function splitstr(str, charToSplit) {
var output = [];
var currentIndex = 0;
var startIndex = 0;
for (var i = 0; i < str.length; i++) {
if (str[i] == charToSplit) {
output[currentIndex] = "";
for (var x = startIndex; x < i; x++) {
output[currentIndex] += str[x];
}
startIndex = i + 1;
currentIndex++;
}
}
output[currentIndex] = "";
for (var i = startIndex; i < str.length; i++) {
output[currentIndex] += str[i];
}
return output;
}
console.log(splitstr("abc|abcd|ac", "|"));
Related
Write a function that accepts a string where letters are grouped together and returns new string with each letter followed by a count of the number of times it appears.
example : ('aeebbccd') should produce // 'a1e2b2c2d1'
function strExpand(str) {
let results = ""
for (let i = 0; i < str.length; i++) {
let charAt = str.charAt(i)
let count = 0
results += charAt
for (let j = 0; j < str.length; j++) {
if (str.charAt(j) === charAt) {
count++;
}
}
results += count;
}
return results;
}
with the input 'aeebbccd' I am getting 'a1e2e2b2b2c2c2d1' instead of 'a1e2b2c2d1'
This function is adding a number after each character, which is the number of times this character appears anywhere in the string. You could instead do it like this to get the result you want.
function strExpand(str) {
let output = "";
// Iterate through each character of the string, appending
// to the output string each time
for (let i = 0; i < str.length; i++) {
let count = 1;
// If the next character is the same, increase the count
// and increment the index in the string
while (str[i + 1] == str[i]) {
count++;
i++;
}
// Add the character and the count to the output string
output += str[i] + count;
}
return output;
}
For sake of completeness,
how about a Regex?
const pattern = /(.)\1*/g; // put a char that exists in a capture group, then see if it repeats directly after
const s = 'aeebbccd';
var result = '';
for (match of s.match(pattern)) {
let this_group = match;
let this_len = match.length;
result = result + this_group[0] + this_len; // get only the first letter from the group
}
console.log(result); // a1e2b2c2d1
This would to the job. edit: hah i see im late :D, but still nice functional way to solve that.
/**
* #param string to count
* #return string $characterA$count. ex. abbccc -> a1b2c3
*/
function toCharacterCountString(str) {
return Array.from(new Set(str).values())
.map(char => {
return `${char}${(str.match(new RegExp(char, "g")) || []).length}`;
}).join('');
}
console.log(toCharacterCountString('abbccc')); // a1b2c3
console.log(toCharacterCountString('aeebbccd')); // a1e2b2c2d1
I would like to duplicate every single letter in my string and uppercasing the first letter.
Like this case:
accum("abcd") -> "A-Bb-Ccc-Dddd".
However, it alters the first letter of the string. I think I should add another iterator called "j". But I don't know how to do it.
Precisely, the only task remaining in my code is to move on to the next letter while saving the changes made for the first letter.
function accum(s) {
var i = 0;
while ( i<s.length){
for (var j =i; j<i ; j++) {
s=s[j].toUpperCase()+s[j].repeat(j)+"-";
i+=1;
}
}
return s.slice(0,s.length-1);
}
Try this:
function accum(s) {
let newString = '';
for(let i = 0; i < s.length; i++) {
newString += s[i].toUpperCase() + s[i].repeat(i) + "-";
}
return newString.slice(0, newString.length - 1);
}
I guess you don't need two repetition loops at all (either you can keep the for or the while, i kept the for).
Your fundamental mistake was in this line: s=s[j].toUpperCase()+s[j].repeat(j)+"-"; where you replaced s with the new string instead of concatenating it (s += instead of s = ). Which would be wrong anyway because you are replacing the original string. You need another empty string to keep the changes separated from the original one.
Do this:
function accum(s) {
accumStr = '';
for (var i=0; i < s.length; i++) {
for (var j = 0; j <= i; j++) {
accumStr += j !== 0 ? s[i] : s[i].toUpperCase();
}
}
return accumStr;
}
console.log(accum('abcd')) //ABbCccDddd
Try this:
function accum(s) {
let strArr = s.split('');
let res = [];
for (let i in strArr) {
res.push(strArr[i].repeat(parseInt(i)+1));
res[i] = res[i].charAt(0).toUpperCase() + res[i].slice(1);
}
return res.join('-');
}
console.log(accum('abcd'))
try to use reduce method
const accum = (str) => {
return [...str].reduce(
(acc, item, index, arr) =>
acc +
item.toUpperCase() +
item.repeat(index) +
(index < arr.length - 1 ? "-" : ""),
""
);
};
console.log(accum("abcd")); //A-Bb-Ccc-Dddd
I'm currently trying to work out how many substrings of a given string are palindromes.
When given the string aabaa the expected output is 5 however my code outputs 4. I'm not too sure why, can any one help me solve this?
My code:
function countPalindromesInString(s) {
let count = 0;
if (s === s.split('').reverse().join('')) {
count += 1;
}
let testStr = '';
for (let i = 0; i < s.length; i++) {
testStr += s[i];
if (testStr === testStr.split('').reverse().join('')) {
count += 1;
}
}
return count;
}
I'm not sure why you expect output 5 for input aabaa.
From my point of view, if you consider a single letter as a palindrome than the output should be 9, otherwise the result should be 4: "aa", "aa", "aba", "aabaa". Your code only count from left to right and also double counts the full 5 letter string, once in the beginning, here:
if (s === s.split('').reverse().join('')) {
count += 1;
}
and once in the for loop for case i=4;
Here is a solution to your question:
function countPalindromesInString(s) {
let count = 0; //or s.length if you chose to count single letters as palindrome
let subString;
for (let i = 1; i < s.length; i++) {
for(let j = 0; j < s.length - i; j++) {
subString = s.substring(j, j+i+1);
if(subString === subString.split('').reverse().join('')) {
count += 1;
}
}
}
return count;
}
Later Edit:
If we want to count unique palindromes in your string, we can store the palindromes found in an array and every time we find another one, we check if it was previously added:
function countPalindromesInString(s) {
let subStrings = [];
for (let i = 0; i < s.length; i++) {
for(let j = 0; j < s.length - i; j++) {
let subString = s.substring(j, j+i+1);
if(subString === subString.split('').reverse().join('') && !subStrings.includes(subString)) {
subStrings.push(subString);
}
}
}
return subStrings.length;
}
I have a function that returns the sum of all its digits For both POSITIVE and NEGATIVE numbers.
I used split method and converted it to string first and then used reduce to add them all. If the number is negative, the first digit should count as negative.
function sumDigits(num) {
var output = [],
sNum = num.toString();
for (var i = 0; i < sNum.length; i++) {
output.push(sNum[i]);
}
return output.reduce(function(total, item){
return Number(total) + Number(item);
});
}
var output = sumDigits(1148);
console.log(output); // --> MUST RETURN 14
var output2 = sumDigits(-316);
console.log(output2); // --> MUST RETURN 4
Instead of returning the sum, it returned 4592 -1264
Am I doing it right or do I need to use split function? Or is there any better way to do this?
Sorry newbie here.
I think you'll have to treat it as a string and check iterate over the string checking for a '-' and when you find one grab two characters and convert to an integer to push onto the array. Then loop over the array and sum them. Of course you could do that as you go and not bother pushing them on the array at all.
function sumDigits(num) {
num = num + '';
var output = [];
var tempNum;
var sum = 0;
for (var i = 0; i < num.length; i++) {
if (num[i] === '-') {
tempNum = num[i] + num[i + 1];
i++;
} else {
tempNum = num[i];
}
output.push(parseInt(tempNum, 10));
}
for (var j = 0; j < output.length; j++) {
sum = sum + output[j];
}
return sum;
}
var output = sumDigits(1148);
console.log(output); // --> MUST RETURN 14
var output2 = sumDigits(-316);
console.log(output2); // --> MUST RETURN 4
How can I get a certain nth element from a string. Like if I want to get every 3rd element from the word GOOGLE how can i do that. SO far i've done this but i dont know what to type after the If
function create_string( string ) {
var string_length=string.length;
var new_string=[];
for( var i=0; i<string_length; i++) {
if(string[i]%3==0) {
}
new_string.push(string[i]);
}
return new_string;
}
Use the charAt() function of String which returns the char at a specific index passed to the function. Using charAt, I have created a script that will return every third character.
var result = "";
for(var i = 2; i < test.length; i+=3){
result += test.charAt(i);
}
If you would like to turn this script into a more reusable function:
var test = "GOOGLE";
function getEveryNthChar(n, str){
var result = "";
for(var i = (n-1); i < test.length; i+=n){
result += str.charAt(i);
}
return result;
}
alert(getEveryNthChar(1,test));
alert(getEveryNthChar(2,test));
alert(getEveryNthChar(3,test));
alert(getEveryNthChar(4,test));
Working Demo: http://jsfiddle.net/Q7Lx2/
Documentation
How about this?
function create_string( string ) {
var string_length=string.length;
var new_string=[];
for( var i=2; i<string_length; i+=3) { // instead of an if, use +=3
new_string.push(string.charAt(i));
}
return new_string.join(""); // turn your array back into a string
}
Note that if you start making this compact, you'll end up with the same answer as Kevin's ;-)
function create_string( s ) {
var new_string = '';
for( var i=2; i<s.length; i+=3) { // instead of an if, use +=3
new_string += s.charAt(i);
}
return new_string;
}
Here's a function that will work for any number, not just 3:
function stringHop(s, n) {
var result = "";
for (var i = 0; i < s.length; i+= n) {
result += s.charAt(i);
}
return result;
}
var foo = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var bar = stringHop(foo, 2); // returns "ACEGIKMOQSUWY"
var baz = stringHop(foo, 3); // returns "ADGJMPSVY"
String.charAt(index) will return the character at the specified index, from 0 to String.length - 1. So:
String.prototype.every = function(n) {
var out = '';
for (var i = 0; i < this.length; i += n) {
out += this.charAt(i);
}
return out;
}
var str = "GOOGLE";
console.log(str.every(3)) // Outputs: GG
If you don't want to include the first character, then change the for loop to:
for (var i = n - 1; i < this.length; i += n) {