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$
  • $\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$ – Q.P. Jan 7 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$ – Q.P. Jan 7 at 16:14
3
$\begingroup$

Try StringDrop:

StringDrop[MyString, -3]

"MyStr"

| improve this answer | |
$\endgroup$
  • $\begingroup$ knocks it out the park. Perfect. $\endgroup$ – Q.P. Jan 7 at 16:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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