对字符串简单加密解密的代码 使用Java语言
时间: 2024-05-14 12:12:42 浏览: 71
加密代码:
```java
public static String encrypt(String input) {
StringBuilder encrypted = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
encrypted.append((char) (c + 1));
}
return encrypted.toString();
}
```
解密代码:
```java
public static String decrypt(String input) {
StringBuilder decrypted = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
decrypted.append((char) (c - 1));
}
return decrypted.toString();
}
```
使用示例:
```java
String originalString = "Hello, world!";
String encryptedString = encrypt(originalString);
System.out.println("Encrypted string: " + encryptedString);
String decryptedString = decrypt(encryptedString);
System.out.println("Decrypted string: " + decryptedString);
```
输出结果:
```
Encrypted string: Ifmmp-xpsme!
Decrypted string: Hello, world!
```
阅读全文