2014-12-07 4 views
2

이것은 지금까지 필자가 작성한 것이다. 공간이 있는지 여부를 확인합니다. 그럴 경우 제거하고 noSpace에 제거 된 공백 문자열을 할당해야합니다. 하지만 난 indexOf 및 하위 문자열을 사용하여 공백을 제거하는 방법을 모르겠다. 누군가 제발 도와 줄 수 있니?문자열에서 공백을 제거하려면 어떻게해야합니까? 단지 indexOf()와 substring()을 사용한다.

public static String removeSpace(String s) 
    { 
    String noSpace = ""; 

    if(s.indexOf(" ") == -1) 
    { 
    noSpace = s; 
    } 

    else 
    { 
    for(int a = 1; a <= s.length(); a++) 
    { 
     if() 
      noSpace = s.substring(0,a); 
    } 

    }  


    return noSpace;   
}  
+0

ThereAre2SpacesConsessConsecutively
당신은 할 수없는, 단지 그 두 기능. 당신은 또한 적어도 'concat'을 필요로합니다. –

+0

그는 할 수 있지만 다른 기능을 사용하는 것이 좋습니다. @HotLicks – afzalex

+0

@HotLicks 내 대답을 참조하십시오, 나는 그것에 대해 잘못 생각할 수 있습니다. –

답변

4

string.indexOf(" ")은 공백이 없을 경우 -1을 반환합니다. 그렇지 않으면, 공간의 첫 번째 인스턴스 색인을 리턴합니다.

int index = s.indexOf(" "); 
if(index != -1) { 
} 

이 그런 공간 후에 인덱스에서 다음이 공간까지 하위 문자열 취함으로써 공간을 잘라, 그리고 :

가 -1이 아닌 다른 뭔가를 반환하는 경우 그래서 당신이해야 할 검사입니다
noSpace = s.substring(0,index) + s.substring(index + 1); 

그게 전부 야!

당신은 이런 식으로 뭔가를 얻을 :

String s = "space testing"; 
while(s.indexOf(" ") != -1) { 
    s = s.substring(0, s.indexOf(" ")) + s.substring(s.indexOf(" ") + 1); 
} 
+0

'trim()'은 불필요한 반복을 저장하지만 앞뒤 공백은 문제가되지 않습니다.이 경우에는 – outlyer

+0

@outlyer 사실입니다. 우리는 그럴 필요가 없습니다 :) 좋은 전화! –

+0

그래서 코드를 테스트했지만 s는 공백을 포함하고 있으므로 while 루프는 무한대가됩니다. 그게 내 컴파일러는 뭐래 – PTheCoolGuy

1

당신은 절단 및 문자열 제거 공백을 추가

String str = "abc asd"; 
while(true){ 
int whiteSpaceIndex = str.indexOf(" "); 
if(whiteSpaceIndex != -1) { 

    // if the space was the last character of String ? 
    // Yes --> then don't care for part after first clip 
    // No --> then append the part after the space character 

    int nextStartIndex = str.length() - whiteSpaceIndex > 1 ? whiteSpaceIndex + 1 : whiteSpaceIndex; 
    if(nextStartIndex != whiteSpaceIndex) { 
    str = str.substring(0, whiteSpaceIndex) + str.substring(nextStartIndex); 
    }else { 
    str = str.substring(0, whiteSpaceIndex) 
    } 
} 
} 
2
당신은 단지 문자열을 재건, 더 이상 공간이 없을 때까지 반복 indexOf()를 호출 할 필요가

substring() 각 공백은 (공백 앞뒤의 부분을 결합하여).

String noSpace = s; 
int idx; 
while (-1 != (idx = noSpace.indexOf(" "))) { 
    noSpace = noSpace.substring(0,idx) + noSpace.substring(idx+1); 
} 
2
public static void main(String[] args) { 

    String testString = " "; 
    System.out.println("Before remmoveSpace:" + testString); 
    System.out.println("After remmoveSpace:" + removeSpace(testString)); 

    testString = " StartWithEmpty"; 
    System.out.println("Before remmoveSpace:" + testString); 
    System.out.println("After remmoveSpace:" + removeSpace(testString)); 

    testString = "There are a few spaces separated by letters "; 
    System.out.println("Before remmoveSpace:" + testString); 
    System.out.println("After remmoveSpace:" + removeSpace(testString)); 

    testString = "There Are2SpacesConsessConsecutively"; 
    System.out.println("Before remmoveSpace:" + testString); 
    System.out.println("After remmoveSpace:" + removeSpace(testString)); 

    } 

    public static String removeSpace(String s) { 

    int firstIndexOfSpace = s.indexOf(" "); 
    if (firstIndexOfSpace == -1) { 
     return s; 
    } else { 
     return s.substring(0, firstIndexOfSpace) 
      + removeSpace(s.substring(firstIndexOfSpace + 1, s.length())); 
    } 

    } 

결과 :
remmoveSpace 전 : remmoveSpace 후
:
remmoveSpace 전 : remmoveSpace 후 StartWithEmpty
: StartWithEmpty
remmoveSpace하기 전에 : 후 문자
로 구분 몇 공간이 있습니다 remmoveSpace : Thereareewewspacesseparatedbyletters
전에 remmoveSpace : Are2SpacesConsessConsecutively
후 remmoveSpace :

관련 문제