1
$\begingroup$

If I have a string

MyString = "MyString"

what is the best way to split it by characters or positions from the right. My current solution is to break the string up into individual characters, get the total length and then use standard list manipulation

ComponentStringList = {{"M"}, {"y"}, {"S"}, {"t"}, {"r"}, {"i"}, \
{"n"}, {"g"}};
StringListLength = Length[ComponentStringList];
SplitPositionFromRight = 3;
Result = ComponentStringList[[1 ;; StringListLength - SplitPositionFromRight]];
StringJoin[ArrayFlatten[Result]] 

This works, but it's ugly and long -- I'm sure there is a better way

$\endgroup$
2
  • $\begingroup$ No. Because StringTake[MyString, -3] will return the last three characters, I want to split the string by characters from the right. I'll take a look at StringPart. $\endgroup$
    – user27119
    Commented Jan 7, 2020 at 16:02
  • $\begingroup$ @Moo StringPart is a good call, but StringDrop is shorter. Still, thanks for the point to StringPart, I'm sure it will come in handy one day. $\endgroup$
    – user27119
    Commented Jan 7, 2020 at 16:14

1 Answer 1

3
$\begingroup$

Try StringDrop:

StringDrop[MyString, -3]

"MyStr"

$\endgroup$
1
  • $\begingroup$ knocks it out the park. Perfect. $\endgroup$
    – user27119
    Commented Jan 7, 2020 at 16:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.