I'm preparing for my interview, faced the problem with the task. The case is that we're having a string: test12pop90java989python
I need to return new string where words will be reversed and numbers will stay in the same place:
test12pop90java989python ==> tset12pop90avaj989nohtyp
What I started with:
Transferring string to char array
Use for loop + Char.IsNumber
??
var charArray = test.ToCharArray(); for (int i = 0; i < charArray.Length; i++) { if (!Char.IsNumber(charArray[i])) { .... } }
but currently I'm stuck and don't know how to proceed, any tips how it can be done?
You can't reverse a run of letters until you've observed the entire run; until then, you need to keep track of the pending letters to be reversed and appended to the final output upon encountering a number or the end of the string. By storing these pending characters in a
Stack<>they are naturally returned in the reverse order they were added.A similar but buffer-free way is to do it is to store the index of the start of the current run of letters, then walk back through and append each character when a number is found...
For both implementations, calling
Transform()with......produces this output...