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.
 将此字符串转换为一个新的字符数组。
时间: 2024-08-01 00:53:48

JAVA字符加密的相关文章

字符加密

实验:字符加密 古罗马皇帝凯撒在打仗时曾经使用过以下方法加密军事情报: 使得ascll加3,XYZ对应ABC 请编写一个程序,使用上述算法加密或解密用户输入的英文字串要求设计思想.程序流程图.源代码.结果截图 (一) (一)设计思路 建立类Enoughcrty (1) 首先输入一个字符串 System.out.println("请输入一个需要加密的字符串:"); 输入字符串Scanner scan =new Scanner(System.in); (2)  返回键盘输入的数据并以Str

Java md5加密 控制台传入与web传入参数 结果不匹配 || 相同字符串加密结果不同

开发中遇到md5加密不一致问题,排除了上下文编码,加密内容问题. 爬了各类资料,最终找到了原因. /** 对字符串进行MD5加密 */ private static String encodeByMD5(String originString) { if (originString != null) { try { // 创建具有指定算法名称的信息摘要 MessageDigest md = MessageDigest.getInstance("MD5"); // 使用指定的字节数组对摘

Java基础加密之BASE64加解密

BASE64加解密,加密与解密实际是指编码(encode)和解码(decode)的过程,其变换是非常简单的,仅仅能够避免信息被直接识别. Base64内容传送编码被设计用来把任意序列的8位字节描述为一种不易被人直接识别的形式. Base64使用A--Z,a--z,0--9,+,/ 这64个字符. Base64是一种很常见的编码规范,其作用是将二进制序列转换为人类可读的ASCII字符序列 Base64编码表 Value Encoding  Value Encoding  Value Encodin

Java Base64加密、解密原理Java代码

Java Base64加密.解密原理Java代码 转自:http://blog.csdn.net/songylwq/article/details/7578905 Base64是什么: Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一,大家可以查看RFC2045-RFC2049,上面有MIME的详细规范.Base64编码可用于在HTTP环境下传递较长的标识信息.例如,在Java Persistence系统Hibernate中,就采用了Base64来将一个较长的唯一标识符(一般为

BZOJ 1031: [JSOI2007]字符加密Cipher 后缀数组

1031: [JSOI2007]字符加密Cipher Time Limit: 10 Sec  Memory Limit: 162 MBSubmit: 6014  Solved: 2503[Submit][Status][Discuss] Description 喜欢钻研问题的JS同学,最近又迷上了对加密方法的思考.一天,他突然想出了一种他认为是终极的加密办法 :把需要加密的信息排成一圈,显然,它们有很多种不同的读法.例如下图,可以读作: JSOI07 SOI07J OI07JS I07JSO 0

bzoj1031[JSOI2007]字符加密

bzoj1031[JSOI2007]字符加密 题意: 一种加密办法是把需要加密的信息排成一圈,显然,它们有很多种不同的读法.把它们按照字符串的大小排序,读出最后一列字符,就是加密后的字符串.给出原字符串,求加密后的字符串. 题解: 将原字符串重复后接在后面,然后求后缀数组,注意求完后要取那些长度大于原字符串长度a2的后缀的第a2个字符. 代码: 1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm>

java字符编码详解

引用自:http://blog.csdn.net/jerry_bj/article/details/5714745 GBK.GB2312.iso-8859-1之间的区别 GB2312,由中华人民共和国政府制定的,简体汉字编码规范,大陆所有计算机中的简体中文,都使用此种编码格式.目前,我也不知道还有另外的简体汉字编码规范.与此对应的还有BIG5,是中华民国政府制定的,繁体汉字的编码规范,一般应用于海外计算机的繁体中文显示.所谓的繁体中文Windows,简体中文Windows,指的就是采用BIG5和

【BZOJ】【1031】【JSOI2007】字符加密Cipher

后缀数组 当年感觉好神的题现在好像变水了…… 题意其实有点蛋疼……一开始没看懂<_< 将原串复制一遍接在后面,用后缀数组求一下SA,那么SA<n的就是所找到的那n个字符串,然后把它们的第n个字符抠出来就可以了…… 1 /************************************************************** 2 Problem: 1031 3 User: Tunix 4 Language: C++ 5 Result: Accepted 6 Time:7

【字符编码】Java字符编码详细解答及问题探讨

一.前言 继上一篇写完字节编码内容后,现在分析在Java中各字符编码的问题,并且由这个问题,也引出了一个更有意思的问题,笔者也还没有找到这个问题的答案.也希望各位园友指点指点. 二.Java字符编码 直接上代码进行分析似乎更有感觉.   运行结果:   说明:通过结果我们知道如下信息. 1. 在Java中,中文在用ASCII码表示为3F,实际对应符号'?',用ISO-8859-1表示为3F,实际对应符号也是为'?',这意味着中文已经超出了ASCII和ISO-8859-1的表示范围. 2. UTF