JAVA字元加密

來源:互聯網
上載者:User

標籤:system.in   jpg   letter   out   ext   from   class   aml   override   

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字元加密

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.