문장에서 단어를 별표로 바꾸려면 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'라는 함수가 포함되어 있습니다. 문장이 분할되어 문자열 배열에 저장됩니다. 빈 문자열이 정의되고 길이에 따라 패턴이 반복됩니다.
별표 값은 '*'로 정의되며 문장의 모든 문자에 대해 해당 문자를 패턴과 비교하고 특정 발생을 별표 기호로 대체합니다. 콘솔에 최종 문자열이 표시됩니다.