Java程序用句子中的星号替换单词
要用句子中的星号替换单词,Java程序如下:
示例
public class Demo{
static String replace_word(String sentence, String pattern){
String[] word_list = sentence.split("\\s+");
String my_result = "";
String asterisk_val = "";
for (int i = 0; i < pattern.length(); i++)
asterisk_val += '*';
int my_index = 0;
for (String i : word_list){
if (i.compareTo(pattern) == 0)
word_list[my_index] = asterisk_val;
my_index++;
}
for (String i : word_list)
my_result += i + ' ';
return my_result;
}
public static void main(String[] args){
String sentence = "This is a sample only, the sky is blue, water is transparent ";
String pattern = "sample";
System.out.println(replace_word(sentence, pattern));
}
}输出结果
This is a ****** only, the sky is blue, water is transparent
名为Demo的类包含一个名为'replace_word'的函数,该函数将句子和模式作为参数。句子被拆分并存储在字符串数组中。定义一个空字符串,并根据其长度对模式进行迭代。
星号值定义为“*”,并且对于句子中的每个字符,将该字符与模式进行比较,并将特定的出现位置替换为星号符号。最终字符串显示在控制台上。