Java에서 문자열 부분 제거


81

한 문자에서 문자열의 일부를 제거하고 싶습니다.

소스 문자열 :

manchester united (with nice players)

대상 문자열 :

manchester united

5
보관할 부분과 폐기 할 부분을 어떻게 알 수 있습니까? 그것을 모르면 질문에 답할 수 없습니까?
Raedwald 2013

답변:


156

이를 수행하는 방법에는 여러 가지가 있습니다. 교체하려는 문자열이 있으면 클래스 의 replace또는 replaceAll메서드를 사용할 수 있습니다 String. 하위 문자열을 교체하려는 경우 substringAPI를 사용하여 하위 문자열을 가져올 수 있습니다 .

예를 들면

String str = "manchester united (with nice players)";
System.out.println(str.replace("(with nice players)", ""));
int index = str.indexOf("(");
System.out.println(str.substring(0, index));

"()"내의 내용을 바꾸려면 다음을 사용할 수 있습니다.

int startIndex = str.indexOf("(");
int endIndex = str.indexOf(")");
String replacement = "I AM JUST A REPLACEMENT";
String toBeReplaced = str.substring(startIndex + 1, endIndex);
System.out.println(str.replace(toBeReplaced, replacement));

약간의 오타. 되어야합니다String toBeReplaced = str.substring(startIndex , endIndex + 1);
Yeung

또한 공백을 제거 할 가치가 있습니다. System.out.println (str.replace ( "(좋은 플레이어 포함)", ""));
kiedysktos

32

문자열 바꾸기

String s = "manchester united (with nice players)";
s = s.replace(" (with nice players)", "");

편집하다:

색인 별

s = s.substring(0, s.indexOf("(") - 1);

3
잊지 마세요s = s.replace(...)
Sergey Kalinichenko

괄호 안의 내용이 변경 될 수 있기 때문에 불가능합니다. 문자에서 문자열을 변경해야합니다 (
zmki

19

String.Replace () 사용 :

http://www.daniweb.com/software-development/java/threads/73139

예:

String original = "manchester united (with nice players)";
String newString = original.replace(" (with nice players)","");

나는 반대 투표자가 아니었지만 아마도 Replace를 잘못된 경우에 넣었 기 때문일까요?
Mike Kwan

1
드라이브 바이 (즉, 설명되지 않고 명백하게 명백한) 반대표의 효과를 무효화하기 위해 찬성했습니다.
Gayot Fow

문자열이 주어진 예제와 같을 필요는 없습니다. 따라서 교체를 사용할 수 없습니다.
Confuse

여기에 성능 비교가 있습니다. String replace 메서드는 내부에서 정규 표현식을 사용합니다. stackoverflow.com/questions/16228992/…
Igor Vuković 2011


7

StringBuilder를 사용 하면 다음과 같은 방법으로 바꿀 수 있습니다.

StringBuilder str = new StringBuilder("manchester united (with nice players)");
int startIdx = str.indexOf("(");
int endIdx = str.indexOf(")");
str.replace(++startIdx, endIdx, "");

6

처음에는 원래 문자열을 "("토큰이있는 문자열 배열로 분할하고 출력 배열의 위치 0에있는 문자열이 원하는 것입니다.

String[] output = originalString.split(" (");

String result = output[0];

5

String 객체의 substring () 메서드를 사용해야합니다.

다음은 예제 코드입니다.

가정 : 여기서는 첫 번째 괄호까지 문자열을 검색하고 싶다고 가정합니다.

String strTest = "manchester united(with nice players)";
/*Get the substring from the original string, with starting index 0, and ending index as position of th first parenthesis - 1 */
String strSub = strTest.subString(0,strTest.getIndex("(")-1);

2

Commons lang에서 StringUtils 사용

null 소스 문자열은 null을 반환합니다. 빈 ( "") 소스 문자열은 빈 문자열을 반환합니다. null 제거 문자열은 소스 문자열을 반환합니다. 빈 ( "") 제거 문자열은 소스 문자열을 반환합니다.

String str = StringUtils.remove("Test remove", "remove");
System.out.println(str);
//result will be "Test"

1
// Java program to remove a substring from a string
public class RemoveSubString {

    public static void main(String[] args) {
        String master = "1,2,3,4,5";
        String to_remove="3,";

        String new_string = master.replace(to_remove, "");
        // the above line replaces the t_remove string with blank string in master

        System.out.println(master);
        System.out.println(new_string);

    }
}

1

"("뒤의 모든 항목을 제거해야하는 경우이 작업을 시도하십시오. 괄호가 없으면 아무 작업도 수행하지 않습니다.

StringUtils.substringBefore(str, "(");

끝 괄호 뒤에 내용이 있으면 시도해보십시오.

String toRemove = StringUtils.substringBetween(str, "(", ")");
String result = StringUtils.remove(str, "(" + toRemove + ")"); 

끝 공백을 제거하려면 str.trim()

Apache StringUtils 함수는 null이고 비어 있으며 일치하지 않음


좋은 해결책 !!
Sumit Shukla

0

replace문자열을 수정 하는 데 사용할 수 있습니다 . 다음은 "("앞의 모든 것을 반환하고 모든 선행 및 후행 공백을 제거합니다. 문자열이 "("로 시작하면 그대로 둡니다.

str = "manchester united (with nice players)"
matched = str.match(/.*(?=\()/)
str.replace(matched[0].strip) if matched

이것은 Java에서 작동하지 않는 것 같습니다. ECMAscript의 파생물 일 수 있습니다. 이 코드가 Java에서와 같이 작동하도록 만드는 방법이 있습니까?
1111161171159459134 2015-07-13

0

Kotlin 솔루션

끝에서 특정 문자열을 제거하는 경우 removeSuffix ( Documentation )

var text = "one(two"
text = text.removeSuffix("(two") // "one"

접미사가 문자열에 없으면 원본을 반환합니다.

var text = "one(three"
text = text.removeSuffix("(two") // "one(three"

문자 뒤를 제거하려면

// Each results in "one"

text = text.replaceAfter("(", "").dropLast(1) // You should check char is present before `dropLast`
// or
text = text.removeRange(text.indexOf("("), text.length)
// or
text = text.replaceRange(text.indexOf("("), text.length, "")

또한 체크 아웃 할 수있다 removePrefix, removeRange, removeSurrounding,하고 replaceAfterLast있는 유사하다

전체 목록은 여기에 있습니다 : ( 문서 )

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.