2013-12-14 2 views
1

사용자가 문자열 str에서 단어를 제거 할 수있게하려고합니다. 예를 들어, "Hello my name is john"을 입력하면 출력은 "Hello is john"이어야합니다. 어떻게해야합니까?문자열의 단어 - 제거하는 방법

import java.util.*; 
class WS7Q2{ 
    public static void main(String[] args){ 
     Scanner in = new Scanner(System.in); 

     System.out.println("Please enter a sentence"); 
     String str = in.nextLine(); 

     int j; 

     String[] words = str.split(" "); 
     String firstTwo = words[0] + " " + words[1]; // first two words 
     String lastTwo = words[words.length - 2] + " " + words[words.length - 1];//last two words 

     System.out.println(str); 

    } 
} 
+3

String.replace ...? – MadProgrammer

+0

'str = str.replace ("my name", "");' –

답변

2

이것은 당신이 인쇄됩니다

String myString = "Hello my name is John"; 

String str = myString.replace("my name", ""); 
System.out.println(str); 

문자열을 분할하는 방법입니다

과 유사한 것을 사용하여 코드에 최소한의 변경으로 str에 새 문자열을 결합 할 수있다 John "

1

왜 사용하지 않을까요 String#replace()

String hello = "Hello my name is john" 

hello = hello.replace("my name", ""); 

System.out.println(hello);