+ 1
My code js not passing 2 tests.What did i do wrong?
The question is:Splitting strings You are given a word and want to split it into even parts based on a number that is provided, each half being the size of the number. Task: Write a program that takes in a string, and a number as input. Split the string into even parts sized by the number, and output the parts separated by hyphens. The last part of the output will be any leftover, as the input string might not split into the provided parts evenly. Input Format: Two inputs: a string and an integer. Output Format: A string, representing the hyphen-separated parts. Sample Input: hello 2 Sample Output: he-ll-o https://code.sololearn.com/c0vfjG5dt4Vm/?ref=app
5 odpowiedzi
+ 3
The issue is that if the string length is not a multiple of the partition size, you access the string out of bounds, which is undefined behaviour. This essentially happens because your inner loop always prints characters equal to the partition size, although the last partition is smaller in the scenario described above.
Possible fix: Simply exit the inner loop if the end of the string has been reached, i.e.
for (int x = 0; x < sil && i < word.size(); ++x)
...
By the way, the variables `o` and `b` are redundant. It is possible to express all conditions/printing in terms of `i` only.
0
Mmh tricky. If you input helloo and the number 2, shouldn‘t the output be hel-loo? Two even parts? That is not the case with your code (output he-ll-oo). Not sure… maybe first check if inputted word length is even. If it‘s odd, run your code. If not… do sth else :)
0
It needs to output turbulence 4
Turb-ulen-ce but it fails
0
So it outputs the number of letters instead. Mmh.
0
Shadow thank you