Shifting String Letters
Hello, I was wondering if somone could steer me in the right direction with shifting each letter in a string over n times (in the alphabet) without using an array.
I was looking at the substring method, but im not quite sure on how to utilize it to perform this operation.
Any help is appreciated thanks
The String method charAt() will return the char value corresponding to a given position in a string. So if the string is "random" then charAt(2) will return 'n'.
char values are actually numeric values: that is you can add/subtract etc with them. So if you wanted you could "shift" the 'n' by two places with the expression 'n'+2. This expression is actually the same as the char value 'p'. The chances are that your "shifting" involves wrapping around at some point so that 'z' --> 'b' or whatever. The arithmetic you use on the char values will have to implement that.
(Read your textbook or online about char)
You could use substring to "extract" a piece of a string. But it seems to me that it is more straightforward to use a numeric data type like char.
Finally note that strings are immutable (=="don't change their content"). This is reflected in the fact that we have a charAt() but no corresponding setCharAt(). Since you can't change a string the next best thing is to create a new string based on the arithmetically altered char values you have constructed. You can concatenate (==join together) things to make string. So, eg, ""+'t'+'c'+'p' will be a string equal to "tcp".
Putting these ideas together you have something that might be expressed somewhat abstractly as:
"random" SHIFT BY 2
charAt(0) 'r' 'r'+2 ('t') ""+('r'+2) "t"
charAt(1) 'a' 'a'+2 ('c') +('a'+2) "tc"
charAt(2) 'n' 'n'+2 ('p') +('n'+2) "tcp"
Clearly some sort of loop is involved here.
If you decide to follow this route and you get stuck, post code so we can see what you're doing.
You're welcome. Good luck!