Remove white space from string without using trim

2020-05-07 23:33发布

given string is '_home sweet home__' if user enter the mode as 0 then o/p should be 'home sweet home__' if user enter the mode as 1 then o/p should be '_home sweet home' if user enter the mode as 2 then o/p should be 'home sweet home'.

Code

public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String");
String str=sc.nextLine();
System.out.println("Enter the StringMode");
String strMode= sc.nextLine();
switch()
{

}

i want to find total number of white spaces in the given string.

标签: java
5条回答
何必那么认真
2楼-- · 2020-05-08 00:05

You could try something like this:

/**
 * Remove white spaces from string according to mode
 * 
 * @param str string
 * @param mode mode 0=leading, 1=trailing, 2=leading+trailing
 * @param result - result buffer
 * @return number of white spaces removed
 */
public int removeWhiteSpacesByMode(String str, int mode, StringBuilder result) {
    int n = 0;
    switch(mode) {
        case 0:
            n = removeLeadingWhiteSpaces(str, result);
            break;
        case 1:
            n = removeTrailingWhiteSpaces(str, result);
            break;
        case 2:
            StringBuilder tmp = new StringBuilder();
            n = removeTrailingWhiteSpaces(str, tmp);
            n += removeLeadingWhiteSpaces(tmp.toString(), result);
            break;
        default:
            throw new IllegalArgumentException("mode=" + mode);
    }
    return n;
}

private int removeTrailingWhiteSpaces(String str, StringBuilder result) {
    int n = 0;
    if(str != null && result != null) {
        n = str.length()-1;
        while(Character.isWhitespace(str.charAt(n))) {
            n--;
        }
        n++;
        for(int j = 0; j < n; j++) {
            result.append(str.charAt(j));
        }
        n = str.length() - n;
    }
    return n;
}

private int removeLeadingWhiteSpaces(String str, StringBuilder result) {
    int n = 0;
    if(str != null && result != null) {
        while(Character.isWhitespace(str.charAt(n))) {
            n++;
        }
        for(int j = n; j < str.length(); j++) {
            result.append(str.charAt(j));
        }
    }
    return n;
}

It makes use a of the method Character#isWhitespace to check whether a character is white space or not and a StringBuilder to build the result. The return value is the number of white paces removed.

If you want to have a method to just count the white spaces in a string you can loop over the entire string, check each character using Character#isWhitespace and increment a variable if it return true.

Finally here is some testing:

@Test
public void removeWhiteSpacesByMode() {
    String str = " home sweet home  ";
    StringBuilder result = null;
    int numberOfWhiteSpacesRemoved = 0;

    numberOfWhiteSpacesRemoved = removeWhiteSpacesByMode(str, 0, null);
    Assert.assertEquals(numberOfWhiteSpacesRemoved, 0);

    result = new StringBuilder();
    numberOfWhiteSpacesRemoved = removeWhiteSpacesByMode(null, 0, result);
    Assert.assertEquals(0, result.length());
    Assert.assertEquals(numberOfWhiteSpacesRemoved, 0);

    try {
        result = new StringBuilder();
        numberOfWhiteSpacesRemoved = 0;
        numberOfWhiteSpacesRemoved = removeWhiteSpacesByMode(null, 4, result);
        Assert.fail("mode 4 should not have been accepted");
    } catch(IllegalArgumentException e) {
        Assert.assertEquals("mode=4", e.getMessage());
        Assert.assertEquals(0, result.length());
        Assert.assertEquals(numberOfWhiteSpacesRemoved, 0);
    }

    result = new StringBuilder();
    numberOfWhiteSpacesRemoved = removeWhiteSpacesByMode(str, 0, result);
    Assert.assertEquals("home sweet home  ", result.toString());
    Assert.assertEquals(numberOfWhiteSpacesRemoved, 1);

    result = new StringBuilder();
    numberOfWhiteSpacesRemoved = removeWhiteSpacesByMode(str, 1, result);
    Assert.assertEquals(" home sweet home", result.toString());
    Assert.assertEquals(numberOfWhiteSpacesRemoved, 2);

    result = new StringBuilder();
    numberOfWhiteSpacesRemoved = removeWhiteSpacesByMode(str, 2, result);
    Assert.assertEquals("home sweet home", result.toString());
    Assert.assertEquals(numberOfWhiteSpacesRemoved, 3);
}
查看更多
爷、活的狠高调
3楼-- · 2020-05-08 00:06

Try this

StringTokenizer t = new StringTokenizer(str," ");
result = t.nextToken();
Boolean first = str.toCharArray()[0]==' ';
Boolean last = str.toCharArray()[str.length()-1]==' ';
while(t.hasMoreTokens())
{
    result += " " + t.nextToken();
}

switch(strMode)
{
    case 0 : if(last) result += " ";
             break;
    case 1 : if(first) result = " " + result;
             break;
}
System.out.println(result);
查看更多
狗以群分
4楼-- · 2020-05-08 00:07

A simple way :

private static String truncateSpace(String text, int mode)
{         
    if(mode==0 || mode==2)   
        for (int i = 0; i < text.length(); i++) {                
        if (text.charAt(i) != ' ') {
            text = text.substring(i, text.length());                
            break;
        }
    }
   if(mode==1 || mode==2)
        for (int i = text.length()-1; i > 0; i--) {
                if (text.charAt(i) != ' ') {
                    text = text.substring(0, i+1);
                    break;
                }
            }       
    return text;
}
查看更多
别忘想泡老子
5楼-- · 2020-05-08 00:17

Do this to remove all the whitespaces. Then, subtract the length of the second string from the length of the first to determine the total number of whitespaces removed.

If you want to remove only the preceding whitespace, use "^\\s+". To remove trailing, use "\\s+$".

查看更多
啃猪蹄的小仙女
6楼-- · 2020-05-08 00:18

A regex-based solution to capture your whitespaces and then rebuild the string according to the mode you need. No loops but requires some knowledge.

public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String");
String str=sc.nextLine();
System.out.println("Enter the StringMode");
int strMode= sc.nextInt();
Pattern pattern = Pattern.compile("^(?<leadingWs>\\s*)(?<text>.+?)(?<trailingWs>\\s*)$");
Matcher matcher = pattern.matcher(str);
matcher.matches(); // should match always
String result = "";
switch(strMode)
{
case 0:
    result = matcher.group("text") + matcher.group("trailingWs");
    break;
case 1:
    result = matcher.group("leadingWs") + matcher.group("text");
    break;
case 2:
    result = matcher.group("text");
    break;
default:
    break;
}
System.out.println("Cleared string: \"" + result + "\"");
System.out.println("Leading whitespace characters: " + matcher.group("leadingWs").length());
System.out.println("Trailing whitespace characters: " + matcher.group("trailingWs").length());
}

It uses named capturing groups to extract your whitespace and reluctant quantifier to get all the text before trailing whitespace characters. See Pattern documentation for capturing groups and this tutorial to get how quantifiers work.

查看更多
登录 后发表回答