Kotlin and use padEnd() twice - string

I tried using padEnd() twice on a String. The first time the padEnd() extension function works as expected, but the second time, it does not add the any characters I tried.
My code:
var s = "Hi -> "
s = s.padEnd(10, 'O')
s = s.padEnd(5, ' ')
println(s)
My output:
Hi -> OOOO
I am using kotlin version 1.2.50. I also tried Jetbrains' online compiler to prevent the bug being only on my computer, with the same result. I also tried using a different version of kotlin (1.0.7 and 1.1.60), with still the same feature/bug.
I also tried using the padStart(), with the same behaviour, just adding it in front of the String.
Mixing the two extension functions also did not work as expected: Using padStart() and immediately after that padEnd()
Is this an expected feature? If so why is it expected? Or is it just a bug?

padEnd doesn't add the given character to your String the given number of times - the first parameter is the target length that it will pad up to. From the docs:
Returns a char sequence of length at least length consisting of this char sequence appended with padChar as many times as are necessary to reach that length.
So in your second call, you're trying to pad "Hi -> 0000" until it's at least 5 characters long - which it already is, so no spaces are added at its end.

You could also do something like:
val outerChar = "*"
val x = outerChar.padEnd(10)
.plus("hello")
.plus(outerChar.padStart(10))
println(x)
// Prints:
// * hello *
This will put 10 spaces between the * and hello on each side. Also try swapping the calls to padEnd and padStart.

Related

How to get the middle of a string in Python?

Hold on: It's not as easy as it sounds in the title.
I've been working on a very crude AI, and the seemingly hard bits have been easy but this one little function is being really hard.
What I want this to do is get some of the chars that occur before a chars in the string. For example,
get_piece_behind("Hello World", 5, 3) #Return the 3 chars that come before ' ' (the fifth char)
'llo'
get_piece_behind("Hello World", 4, 3) #Return the 3 chars that come before 'o' in "hello" (the fourth char)
'ell'
get_piece_behind("Hello World", 5, 2) #Return the 2 chars that come before the fifth char
'lo'
The code accepts a string, an int marking a place in the string, and an int telling the function how far back it should look.
I get the idea this should be a super-simple one-liner... but my coffee infused brain has been staring at it for the past hour, rewriting it over and over, and nothing seems to work (my current function returns small bits of string, but from the wrong place)
def get_piece_behind(string, place, length_of_piece): #My current function
string = string[(place - length_of_piece):]
string = string[:place]
return string
Does anyone know how to fix this? I get the idea that it's a tiny, stupid error that I will have completely overlooked.
Thanks!
Python strings are sequences, and as such you can use the slice-index syntax to retrieve sub-sequeces of it:
a = "hello world"
a[1:3] # retrieves the chars from the second posistion (index 1) up to the 4th.
# the same, but as you want, putting expressins to calculate the indexes:
a[5-3:5]
a[4-3:4]
I suggest you to read the following document in whole before proceeding with your task - might save you a lot of time:
https://docs.python.org/3/tutorial/introduction.html
You are overlooking in your string splicing.
Try this:
def get_piece_behind(string, place, length_of_piece):
string = string[(place-length_of_piece) : place]
return string
Just do it in one line :) since your string change after first reassignment, also character positions will change:
def get_piece_behind(_string, place, length_of_piece): #My current function
_string = _string[(place - length_of_piece):place]
return _string
The index of characters changes as you cut first with place - length_of_piece, which gives 2, so you were cutting from third char, "llo World" then 5 characters before, resulting in "llo W".
This should work for you:
def get_piece_behind(string, place, length_of_piece):
return string[place-length_of_piece:place]
Output:
llo
ell
lo

what does this syntax error means. I wrote my code good. What is the problem?

why do I get this problem: SyntaxError: EOL while scanning string literal. Can someone please tell me where my fault is.
a = 2
b = 4
c = 8
print ("Forced Order:" 'a', '*' ('c' '+' 'b') '=’ a*(c+b))
The EOL error specifically appears because of '*' ('c' '+' 'b'). The computer believes that this code is trying to run a function, much like print(). The error pops up because a string cannot call a function like this.
What I imagine your trying to do is make the function output is Forced Order: a*(c+b)=24.That can be solved with two quick fixes:
First, there's a typo. '=’ should use ' not ’ on both sides.
Second, the parenthesis need to be parts of the string. The parenthesis in ('c' '+' 'b') are not part of any strings. Either they can be individually turned into strings like the rest of the function or, just like with the string "Forced Order:", the string "a*(c+b)" can be written out as one string instead of concatenating a series of single characters.

Remove part of string (regular expressions)

I am a beginner in programming. I have a string for example "test:1" and "test:2". And I want to remove ":1" and ":2" (including :). How can I do it using regular expression?
Hi andrew it's pretty easy. Think of a string as if it is an array of chars (letters) cause it actually IS. If the part of the string you want to delete is allways at the end of the string and allways the same length it goes like this:
var exampleString = 'test:1';
exampleString.length -= 2;
Thats it you just deleted the last two values(letters) of the string(charArray)
If you cant be shure it's allways at the end or the amount of chars to delete you'd to use the version of szymon
There are at least a few ways to do it with Groovy. If you want to stick to regular expression, you can apply expression ^([^:]+) (which means all characters from the beginning of the string until reaching :) to a StringGroovyMethods.find(regexp) method, e.g.
def str = "test:1".find(/^([^:]+)/)
assert str == 'test'
Alternatively you can use good old String.split(String delimiter) method:
def str = "test:1".split(':')[0]
assert str == 'test'

Why am I getting a StringIndexOutOfBoundsException?

for(int i=0;i<5;i++)
{
char ans = s.next().charAt(i);
}
I am getting a StringIndexOutOfBoundsException. Why it is happening?
Because s.next() is returning a String with less than 5 characters. Try printing out s.next() to see the value if you expected it to be longer.
You are getting the exception cause you are trying to assign a char in your "ans" variable which is not available. The reason behind this is, the string you're getting by calling the 's.next()' method is not returning a string with at least 5 characters. Let's say the string is "Me" and you're trying to loop through it 5 times where there is only two characters. So when you're trying to look for the 3rd indexed character there is none and so you're getting the "StringIndexOutOfBoundsException"......
You can also re-use the Scanner object, there's no need to create a new one for each user input.
And: "charCount = charCount++;" --> "charCount++;"

Multiline string literal in Matlab?

Is there a multiline string literal syntax in Matlab or is it necessary to concatenate multiple lines?
I found the verbatim package, but it only works in an m-file or function and not interactively within editor cells.
EDIT: I am particularly after readbility and ease of modifying the literal in the code (imagine it contains indented blocks of different levels) - it is easy to make multiline strings, but I am looking for the most convenient sytax for doing that.
So far I have
t = {...
'abc'...
'def'};
t = cellfun(#(x) [x sprintf('\n')],t,'Unif',false);
t = horzcat(t{:});
which gives size(t) = 1 8, but is obviously a bit of a mess.
EDIT 2: Basically verbatim does what I want except it doesn't work in Editor cells, but maybe my best bet is to update it so it does. I think it should be possible to get current open file and cursor position from the java interface to the Editor. The problem would be if there were multiple verbatim calls in the same cell how would you distinguish between them.
I'd go for:
multiline = sprintf([ ...
'Line 1\n'...
'Line 2\n'...
]);
Matlab is an oddball in that escape processing in strings is a function of the printf family of functions instead of the string literal syntax. And no multiline literals. Oh well.
I've ended up doing two things. First, make CR() and LF() functions that just return processed \r and \n respectively, so you can use them as pseudo-literals in your code. I prefer doing this way rather than sending entire strings through sprintf(), because there might be other backslashes in there you didn't want processed as escape sequences (e.g. if some of your strings came from function arguments or input read from elsewhere).
function out = CR()
out = char(13); % # sprintf('\r')
function out = LF()
out = char(10); % # sprintf('\n');
Second, make a join(glue, strs) function that works like Perl's join or the cellfun/horzcat code in your example, but without the final trailing separator.
function out = join(glue, strs)
strs = strs(:)';
strs(2,:) = {glue};
strs = strs(:)';
strs(end) = [];
out = cat(2, strs{:});
And then use it with cell literals like you do.
str = join(LF, {
'abc'
'defghi'
'jklm'
});
You don't need the "..." ellipses in cell literals like this; omitting them does a vertical vector construction, and it's fine if the rows have different lengths of char strings because they're each getting stuck inside a cell. That alone should save you some typing.
Bit of an old thread but I got this
multiline = join([
"Line 1"
"Line 2"
], newline)
I think if makes things pretty easy but obviously it depends on what one is looking for :)

Resources