0

给定的字符串是 ' _ home sweet home __ ' 如果用户进入模式为 0 那么 o/p 应该是 'home sweet home__' 如果用户输入模式为 1 那么 o/p 应该是 '_home sweet home' 如果用户输入模式为 2,那么 o/p 应该是 'home sweet home'。

代码

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()
{

}

我想在给定的字符串中找到空格的总数。

4

5 回答 5

1

这样做可以删除所有空格。然后,从第一个字符串的长度中减去第二个字符串的长度,以确定删除的空格总数。

如果您只想删除前面的空格,请使用“^\\s+”。要删除尾随,请使用“\\s+$”。

于 2013-10-26T23:00:45.827 回答
1

你可以尝试这样的事情:

/**
 * 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;
}

它使用Character#isWhitespace方法来检查字符是否为空格,并使用StringBuilder来构建结果。返回值是删除的白色步数。

如果你想有一个方法来计算字符串中的空格,你可以遍历整个字符串,使用Character#isWhitespace检查每个字符,如果它返回 true,则增加一个变量。

最后是一些测试:

@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);
}
于 2013-10-27T19:20:40.107 回答
0

一个基于正则表达式的解决方案,用于捕获您的空格,然后根据您需要的模式重建字符串。没有循环,但需要一些知识。

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());
}

它使用命名的捕获组来提取你的空格和不情愿的量词来获取尾随空格字符之前的所有文本。请参阅用于捕获组的模式文档和教程以了解量词的工作原理。

于 2013-10-27T19:41:02.527 回答
0

尝试这个

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);
于 2013-10-26T23:11:17.503 回答
0

一个简单的方法:

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;
}
于 2017-07-26T07:01:02.490 回答