Remove white space from string without using trim method?

后端 未结 5 1446
轮回少年
轮回少年 2021-01-27 12:10

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 mod

5条回答
  •  逝去的感伤
    2021-01-27 12:48

    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("^(?\\s*)(?.+?)(?\\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.

提交回复
热议问题