Parse the string for \

A project log for Remote control and image retrieval from Nikon DSLR

This post explains how to control a Nikon D3100 DSLR, and then get the images off of it.

sciencedude1990sciencedude1990 12/10/2020 at 03:342 Comments

Here is the helper function that, for every '\' in the path, it makes sure it is \\ so that printf works correctly...


function [ret] = parse_dir_add_slash(dir_in)

% Search for the '\' character in the string
temp = strfind(dir_in, '\');

% For every \ in the string, make sure it is \\ so that it will print correctly
ret = '';
if ~isempty(temp)
    for ii = 1 : length(temp)
        if ii == 1
            ret = [ret dir_in(1 : (temp(ii) - 1)) '\\'];
            ret = [ret dir_in((temp(ii - 1) + 1) : (temp(ii) - 1)) '\\'];

% If the input string doesn't end with a \, add the rest of the string
if temp(end) < length(dir_in)
    ret = [ret dir_in((temp(end) + 1) : end)];


sciencedude1990 wrote 12/10/2020 at 13:51 point

Hi Ken,

Unfortunately, MATLAB will take the printf statement,

fprintf('Hi there\n Ken', '%s')

and generate:

Hi there

It will still process \n as a newline.

Yeah - there is probably one of the regular expressions or built in functions that you could use, but since I wanted to make this post useful to non-Matlab users, I went with the simple step by step, ultra-commented post.


  Are you sure? yes | no

Ken Yap wrote 12/10/2020 at 06:31 point

Isn't there a function to substitute every \ with \\ in the string? That would fix the string in one fell swoop.

The other thing that occurs to me, on the assumption that matlab printf is similar to C printf, is you should be doing

printf("%s", path)

instead of


This way, no characters in path have to be escaped.

  Are you sure? yes | no