By looking at the output it seems that you want two backward slashes for rahul and sam respectively. Because input string is having only two "\\" (for each of them) the first one behaves as escape character for the second one. (It tells compiler that succeeding \ should be literally considered as backward slash.) And so you end up having only one \ in your output. Can you change i/p string? This is what I thought after looking at your desired output.