Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I'm trying to use Mathematica to make some work on binary data, and I'm missing something.

Consider the string "111". I want to flip the last bit to become "110". My guess would be to use StringReplacePart, but I'm struggling to achieve this:

StringReplacePart["111", "0", 3]  (* returns "0" *)

What is the function for replacing a single character at a given position?

share|improve this question
1  
You need {3, 3} as the last argument... that's the only documented form. It looks like using just 3 is equivalent to {1, 3}, but is undocumented. –  rm -rf Jan 8 at 16:04
    
-.-' I needed it in a middle position and because, strangely enough, StringReplacePart["111", "0", -1] works, I assumed the notation was consistent. Thanks @rm-rf, feel free to add an answer. –  J. C. Leitão Jan 8 at 16:08
    
The last part of my answer explains why -1 worked differently. It seems like for negative indices, it is equivalent to {n, -1}. –  rm -rf Jan 8 at 16:23

1 Answer 1

up vote 1 down vote accepted

The documented form of StringReplacePart is

StringReplacePart["string", "snew", {m, n}]

where the replacement is done from positions m through n. In your case, you would need {3, 3}:

StringReplacePart["111", "0", {3, 3}]
(* "110" *)

You can also use -1 as the index for the last element (useful when the string length is unknown).


Using only an integer n as the last argument doesn't seem to be documented, but from a quick test, it appears to be the same as {1, n} for positive n and {n, -1} for negative n.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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