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'的函数,该函数将句子和模式作为参数。句子被拆分并存储在字符串数组中。定义一个空字符串,并根据其长度对模式进行迭代。
星号值定义为“*”,并且对于句子中的每个字符,将该字符与模式进行比较,并将特定的出现位置替换为星号符号。最终字符串显示在控制台上。
热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练