StringExamples

public class StringExamples

{

    // String concatenation

    // char evaluation/arithmetic

    

    public static String rot13 (String plaintext)

    {

        return shiftCipher(plaintext, 13);

    }

    

    public static String shiftCipher(String plaintext, int shift)

    {

        String result = ""; // result is an empty string

        

        for (int pos = 0; pos < plaintext.length(); pos++)

        {

            // Get current character

            char next = plaintext.charAt(pos);

            

            if ( (next >= 'a' && next <= 'z') || 

                 (next >= 'A' && next <= 'Z') )

            {            

                int offset;

                

                if (next >= 'a' && next <= 'z')

                {

                    offset = next - 'a'; // Convert char to 0-25

                }

                else

                {

                    offset = next - 'A';

                }

                

                offset = offset + shift; // Shift some number of positions forward

                

                while (offset > 25) // Account for extreme offset values

                {

                    offset = offset - 26;

                }

                

                while (offset < 0)

                {

                    offset = offset + 26;

                }

                

                char newChar;

                

                if (next >= 'a' && next <= 'z')

                {

                    newChar = (char)(offset + 'a');

                }

                else

                {

                    newChar = (char)(offset + 'A');

                }

                

                result = result + newChar;

            }

            else

            {

                result = result + next; // Ignore non-letters

            }

        } // end of loop

        

        return result;

    }

}

This page was last modified on 8/25/09