Tag Archives: String

Java encrypts the string with MD5

for a plaintext, for security, sometimes we need to do MD5 encryption, the following provides a Java tool method, directly called.

/**
 * MD5加密
 */
public class MD5Util {

	/**
	 * Encodes a string 2 MD5
	 * 
	 * @param str String to encode
	 * @return Encoded String
	 * @throws NoSuchAlgorithmException
	 */
	public static String crypt(String str) {
		if (str == null || str.length() == 0) {
			throw new IllegalArgumentException("String to encript cannot be null or zero length");
		}
		StringBuffer hexString = new StringBuffer();
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes());
			byte[] hash = md.digest();
			for (int i = 0; i < hash.length; i++) {
				if ((0xff & hash[i]) < 0x10) {
					hexString.append("0" + Integer.toHexString((0xFF & hash[i])));
				} else {
					hexString.append(Integer.toHexString(0xFF & hash[i]));
				}
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return hexString.toString();
	}

}


Translate() and maketrans() methods of string in Python

Explained

use translate to replace specific characters in a string, such as 12345 for aeiou. Using translate requires the maketrans method to build the replacement table
note: python2’s maketrans method needs to be imported, whereas python3 is built in. In python3, using the syntax of python2 to import: ImportError: cannot import name ‘maketrans’

str.maketrans()

python document interpretation

Help on built-in function maketrans in str:

str.maketrans = maketrans(...)
    Return a translation table usable for str.translate().

    If there is only one argument, it must be a dictionary mapping Unicode
    ordinals (integers) or characters to Unicode ordinals, strings or None.
    Character keys will be then converted to ordinals.
    If there are two arguments, they must be strings of equal length, and
    in the resulting dictionary, each character in x will be mapped to the
    character at the same position in y. If there is a third argument, it
    must be a string, whose characters will be mapped to None in the result.

str.translate()

python document interpretation

Help on method_descriptor in str:

str.translate = translate(self, table, /)
    Replace each character in the string using the given translation table.
    
      table
        Translation table, which must be a mapping of Unicode ordinals to
        Unicode ordinals, strings, or None.
        
The table must implement lookup/indexing via __getitem__, for instance a
    dictionary or list.  If this operation raises LookupError, the character is
    left untouched.  Characters mapped to None are deleted.

Example

replace aeiou with 12345


trantab = str.maketrans("aeiou", "12345")

print ("EXAMPLE:aeiou".translate(trantab))

Output

is

EXAMPLE:12345

Regular expressions filter special characters

 String regEx="[`~!@#$%^&*()_\\-+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";  
        Pattern   p   =   Pattern.compile(regEx);     
        Matcher   m   =   p.matcher(searchKeyWord);     
        searchKeyWord =  m.replaceAll("").trim(); 

matches Chinese, regular expression: [\u4E00-\u9FA5] because the range of Chinese unicode code is this.

matches Numbers, [0-9 b|.] this matches integers and decimals.

matches English letters, [a-z| a-z] matches upper and lower case English characters.

whitespace characters, [\s] may need to be written [\\s] in the program so that \r,\n,\t,space, and other whitespace characters can match, instead of whitespace characters just adding a ^, write: [^\\s]

How to convert a Java string into a number (stringtonumber)

public class StringToNumber {
    public static void main(String[] args) {
        String str = "123";

        Integer num1 = new Integer(str);

        int num2 = Integer.parseInt(str);

        Integer num3 = Integer.valueOf(str);

        System.out.println(num1+"\t"+num2+"\t"+num3);

    }
}

if it’s a single character or a string you have to cut it and convert it to char and then convert it to char otherwise it will be null pointer exception

like above

String a = "ABC";

//将String对象中的每一个下标位的对象保存在数组中

char[] b = a.toCharArray();

//转换成响应的ASCLL

for (char c : b) {

System.out.println(Integer.valueOf(c));

}

principle analysis:

Interger class constructor

directly into the source code, look at this constructor:

 
  1. public Integer(String s) throws NumberFormatException {

  2. this.value = parseInt(s, 10);

  3. }

What is

this this.value?Continue tracing source:

 private final int value;

from this, we can find a characteristic of the packaging class:

inside the wrapper, the corresponding primitive data type of the wrapper class is treated as a private attribute, and the value of the primitive data type is wrapped externally into an object of the corresponding wrapper class.

in the constructor of an Integer, we find that the parseInt (String s) method is called, and we continue our tracing, which leads us to the second method demonstrated at the beginning of this article:

parseInt (String s) method

 
  1. public static int parseInt(String s) throws NumberFormatException {

  2. return parseInt(s,10);

  3. }

  4. // a: the first method of encapsulation,

  5. // a:

  6. public static int parseInt(String s, int radix)throws NumberFormatException

valueOf (String s) method

 
  1. public static Integer valueOf(String s) throws NumberFormatException {

  2. return Integer.valueOf(parseInt(s, 10));

  3. }

The last method,

, actually calls the parseInt() method (the second)