输入计算机学院,判断字符串是否含有院字,如果有用*代替。编写java代码
时间: 2024-03-21 18:37:48 浏览: 11
可以使用字符串的contains()方法来判断是否包含子字符串,并使用replace()方法将子字符串替换为指定字符。以下是Java代码示例:
```java
public class Test {
public static void main(String[] args) {
String str = "计算机学院";
if (str.contains("院")) {
str = str.replace("院", "*");
}
System.out.println(str); // 输出:计算机学*
}
}
```
在这个示例中,我们首先判断字符串中是否包含子字符串"院",如果包含就使用replace()方法将其替换为"*",最后输出替换后的字符串。
相关问题
用JAVA语言编写一个加密处理程序,从键盘输入一段英文文字,将其中每个字母用其后的第4个字母代替,最后的字母轮回到前面去数,其他符号不变。例如,a用e代替,z用d代替
以下是用JAVA语言编写的一个加密处理程序:
```java
import java.util.Scanner;
public class Encryptor {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入要加密的英文文字:");
String input = scanner.nextLine();
String output = encrypt(input);
System.out.println("加密后的文字为:" + output);
}
private static String encrypt(String input) {
char[] chars = input.toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if (c >= 'a' && c <= 'z') {
c += 4;
if (c > 'z') {
c -= 26;
}
} else if (c >= 'A' && c <= 'Z') {
c += 4;
if (c > 'Z') {
c -= 26;
}
}
chars[i] = c;
}
return new String(chars);
}
}
```
程序运行后,会提示用户输入要加密的英文文字,然后将输入的文字进行加密处理,并输出加密后的结果。加密处理的具体过程如下:
1. 将输入的文字转换为字符数组;
2. 遍历每个字符,如果是小写字母,则将其加上4,并判断是否超出字母表范围,如果超出则轮回到前面去数;如果是大写字母,则同样进行加密处理;
3. 将加密后的字符数组转换为字符串,并返回。
不使用String类中的方法,自己编写一个Java程序代替String类中的charAT(int index)方法
下面是一个自己编写的Java程序代替String类中的charAt(int index)方法的示例代码:
```
public class CustomString {
private char[] chars;
public CustomString(String str) {
this.chars = str.toCharArray();
}
public char charAt(int index) {
if (index < 0 || index >= chars.length) {
throw new IndexOutOfBoundsException();
}
return chars[index];
}
}
```
在上面的示例代码中,我们自己定义了一个名为CustomString的类,它有一个私有的char类型数组,可以使用构造函数将字符串转换为这个数组。我们在自己编写的charAt方法中,先判断索引是否越界,如果越界则抛出IndexOutOfBoundsException异常;否则直接返回在索引位置上的字符。