首页 > 代码库 > JAVA字符加密

JAVA字符加密

1、字符加密解密

古罗马皇帝凯撒在打仗时曾经使用过以下方法加密军事情报:

技术分享

 

请编写一个程序,使用上述算法加密或解密用户输入的英文字串。

(1)源代码:

import java.util.Scanner;
 
public class Jiami {
  
     public static void main(String[] args) {
         // TODO Auto-generated method stub
        Scanner scan = new Scanner(System.in);
         String str = scan.next(); 
         String jm = jiaMi(str);
         System.out.println("将 " + str + " 加密结果 " + jm);  
         jm = jieMi(str);
         System.out.println("将 " + str + " 解密结果 " + jm);
         scan.close();
}       
public static String jiaMi(String str){          StringBuffer jm = new StringBuffer();          char ch;          for(int i = 0;i < str.length();i++){              if(  (str.charAt(i) >= ‘x‘ && str.charAt(i) <= ‘z‘)   ||   (str.charAt(i) >= ‘X‘ && str.charAt(i) <= ‘Z‘)  )
{                  ch
= (char) (str.charAt(i) - 23);                  jm.append(ch);              }              else
{                  ch = (char) (str.charAt(i) + 3);                  jm.append(ch);              }          }           return jm.toString();      }      public static String jieMi(String str)
{          StringBuffer jm
= new StringBuffer();          char ch;          for(int i = 0;i < str.length();i++)
{              
if(  (str.charAt(i) >= ‘a‘ && str.charAt(i) <= ‘c‘)   ||   (str.charAt(i) >= ‘A‘ && str.charAt(i) <= ‘C‘)  )
{                  ch
= (char) (str.charAt(i) + 23);                  jm.append(ch);              }              else
{                  ch = (char) (str.charAt(i) - 3);                    jm.append(ch);              }          }           return jm.toString();      } }

 

(2)程序截图

技术分享

(3)程序设计思想:

    读入字符串,

    加密:遍历该字符串,如果该字符串原先为 x , y , z则减去23,否则加上3

    解密:遍历该字符串,如果该字符串原先为 a , b , c则加上23,否则减去3

 

(4)程序流程图:

技术分享

 

2、字符串相等

(1)"=="判断引用的地址是否相等,equals()方法比较的是值是否相等;

(2)字符串为不可变量,使用 ‘+‘ , 相当于得到了一个新的字符串对象(地址不同)。

 

3、String类的Length()、charAt()、 getChars()、replace()、 toUpperCase()、 toLowerCase()、trim()、toCharArray()使用说明

(1)length

public int length()
Returns the length of this string. The length is equal to the number of Unicode code units in the string.
Specified by:
length in interface CharSequence
Returns:
the length of the sequence of characters represented by this object.
返回此字符串的长度。
例如:

String str = "Hello";
System.out.println(str.length()); //5

(2)charAt

public char charAt(int index)
Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.

If the char value specified by the index is a surrogate, the surrogate value is returned.

Specified by:
charAt in interface CharSequence
Parameters:
index - the index of the char value.
Returns:
the char value at the specified index of this string. The first char value is at index 0.
Throws:
IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string.
返回指定索引处的 char 值。
例如:

String str = "Hello";
System.out.println(str.charAt(2));//  l

(3)getChars

public void getChars(int srcBegin,
                     int srcEnd,
                     char[] dst,
                     int dstBegin)
Copies characters from this string into the destination character array.

The first character to be copied is at index srcBegin; the last character to be copied is at index srcEnd-1 (thus the total number of characters to be copied issrcEnd-srcBegin). The characters are copied into the subarray of dst starting at index dstBegin and ending at index:

     dstBegin + (srcEnd-srcBegin) - 1
 
Parameters:
srcBegin - index of the first character in the string to copy.
srcEnd - index after the last character in the string to copy.
dst - the destination array.
dstBegin - the start offset in the destination array.
Throws:
IndexOutOfBoundsException - If any of the following is true:
  • srcBegin is negative.
  • srcBegin is greater than srcEnd
  • srcEnd is greater than the length of this string
  • dstBegin is negative
  • dstBegin+(srcEnd-srcBegin) is larger than dst.length

 将字符从此字符串复制到目标字符数组。

(4)replace

public String replace(char oldChar,
                      char newChar)
Returns a string resulting from replacing all occurrences of oldChar in this string with newChar.

If the character oldChar does not occur in the character sequence represented by this String object, then a reference to this String object is returned. Otherwise, a String object is returned that represents a character sequence identical to the character sequence represented by this String object, except that every occurrence of oldChar is replaced by an occurrence of newChar.

Examples:

 "mesquite in your cellar".replace(‘e‘, ‘o‘)
         returns "mosquito in your collar"
 "the war of baronets".replace(‘r‘, ‘y‘)
         returns "the way of bayonets"
 "sparring with a purple porpoise".replace(‘p‘, ‘t‘)
         returns "starring with a turtle tortoise"
 "JonL".replace(‘q‘, ‘x‘) returns "JonL" (no change)
 
Parameters:
oldChar - the old character.
newChar - the new character.
Returns:
a string derived from this string by replacing every occurrence of oldChar with newChar.
返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。

(5)toUpperCase

public String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale. This method is equivalent to toUpperCase(Locale.getDefault()).

Note: This method is locale sensitive, and may produce unexpected results if used for strings that are intended to be interpreted locale independently. Examples are programming language identifiers, protocol keys, and HTML tags. For instance, "title".toUpperCase() in a Turkish locale returns "T\u0130TLE", where ‘\u0130‘ is the LATIN CAPITAL LETTER I WITH DOT ABOVE character. To obtain correct results for locale insensitive strings, use toUpperCase(Locale.ROOT).

 

Returns:
the String, converted to uppercase.
See Also:
toUpperCase(Locale)
 使用默认语言环境的规则将此 String 中的所有字符都转换为大写。

(6)toLowerCase

public String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale. This is equivalent to calling toLowerCase(Locale.getDefault()).

Note: This method is locale sensitive, and may produce unexpected results if used for strings that are intended to be interpreted locale independently. Examples are programming language identifiers, protocol keys, and HTML tags. For instance, "TITLE".toLowerCase() in a Turkish locale returns "t\u0131tle", where ‘\u0131‘ is the LATIN SMALL LETTER DOTLESS I character. To obtain correct results for locale insensitive strings, use toLowerCase(Locale.ROOT).

 

Returns:
the String, converted to lowercase.
See Also:
toLowerCase(Locale)
 使用默认语言环境的规则将此 String 中的所有字符都转换为小写。

(7)trim

public String trim()
Returns a string whose value is this string, with any leading and trailing whitespace removed.

If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes greater than ‘\u0020‘ (the space character), then a reference to this String object is returned.

Otherwise, if there is no character with a code greater than ‘\u0020‘ in the string, then a String object representing an empty string is returned.

Otherwise, let k be the index of the first character in the string whose code is greater than ‘\u0020‘, and let m be the index of the last character in the string whose code is greater than ‘\u0020‘. A String object is returned, representing the substring of this string that begins with the character at index k and ends with the character at index m-that is, the result of this.substring(k, m + 1).

This method may be used to trim whitespace (as defined above) from the beginning and end of a string.

Returns:
A string whose value is this string, with any leading and trailing white space removed, or this string if it has no leading or trailing white space.
返回字符串的副本,忽略前导空白和尾部空白。

(8)toCharArray

public char[] toCharArray()
Converts this string to a new character array.
Returns:
a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.
 将此字符串转换为一个新的字符数组。

JAVA字符加密