0

I am working on a ShiftCipher program, and i'm looking to convert a string sentence (" This is an example") to chars, to i can shift the sentence over 2 letters. Input: "THIS IS AN EXAMPLE" output:"VJKU KU CP GZCORNG"

with the spaces intact. But i'm not sure how I can convert it to a char, shift the text and then convert it back into a char.

Jordan Benge
  • 1,053
  • 1
  • 13
  • 30
  • 1
    I'd advise reading the javadoc for the `String` class. You'll find useful methods there, and remember that a char is an unsigned 16 bit value that can be incremented just like an int. – Kayaman Apr 07 '14 at 16:54
  • you can do it with `charAt` or `indexOf`, check if it's an space, if true, skip it, else make your algorithm – Frakcool Apr 07 '14 at 16:55
  • one google away: http://stackoverflow.com/questions/10006165/converting-string-to-character-array-in-java – Bogdan M. Apr 07 '14 at 16:59

1 Answers1

1

First you have to convert string into char array. Do this:

String str = "Your input"; 
char[] charArray = str.toCharArray();

Then you will have to loop through every single char and shift it over by 2.

for(int i = 0; i < charArray.length; i++)
    charArray[i] += 2;

And then convert the char array with shifted characters back to string.

String output = new Strin(charArray);

And there you have it.

I do advice you read up on String class but if you do not and simply copy my answer, then no one will cry for you because you fail the class by not putting effort into homework.

Quillion
  • 6,346
  • 11
  • 60
  • 97
  • Thanks, i figured it out before i saw your answer actually. But i appreciate the advice. – Jordan Benge Apr 16 '14 at 20:24
  • @user3507670 Glad I could be of some help. However please, mark as solved so we can move along and so that this does not show up in the unanswered queue. – Quillion Apr 16 '14 at 20:27