【问题标题】:Java trim character and whitespacesJava 修剪字符和空格
【发布时间】:2016-05-19 03:02:51
【问题描述】:

阅读 Java TestNG 测试顶部的注释,我的注释为:

@TestInfo(id={ " C26603", " C10047" }) 

其中TestInfo 只是具有id() as String array 的接口:

public String[] id() default {};

C26603C10047 只是我分配的测试ID。

这是测试结构的样子(例如):

案例 1

@TestInfo(id={ " C26603", " C10047" })
public void testDoSomething() {
     Assert.assertTrue(false);
}

类似的更简洁的情况是:

案例 2:

@TestInfo(id={ "C26603", "C10047" })

如您所见,案例 2 比案例 1 更清晰。案例 2 在测试 ID 中没有空格。

我如何获取这些 id 并确保它们的开头没有那个 C 字符而只是一个纯数字?例如,我只想要 @我的第一个 ID 为 987654330@,第二个 ID 为 10047。 id 数组中有一些空格(引号内)。我想修剪所有内容(如空格)并获取 id。我目前正在应用for loop 来处理每个 id,一旦我得到纯数字,我想进行第 3 方 API 调用(API 期望纯数字作为输入,因此删除 C 作为初始字符和其他空格很重要) .

这是我尝试过的:

TestInfo annotation = method.getAnnotation(TestInfo.class);
if(annotation!=null) {
        for(String test_id: annotation.id()) {
            //check if id is null or empty
            if (test_id !=null && !test_id.isEmpty()) {
         //remove white spaces and check if id = "C1234" or id = "1234"
                    if(Character.isLetter(test_id.trim().charAt(0))) {
                                test_id = test_id.substring(1);
                    }
                    System.out.println(test_id);
                    System.out.println(test_id.trim());
            }
      }
}

上面的代码给了我C26603not 26603,适用于案例1。它适用于案例2。

案例 3:

@TestInfo(id={ " 26603", " 10047" })

对于这种情况,没有 C 作为测试 id 的开头字符,因此该函数应该足够聪明,可以只修剪空白并继续执行。

【问题讨论】:

  • 我简要浏览了您的个人资料,由于您是一个相当新的用户,您能看看this吗?如果您奖励帮助您的人,您将获得更好的 SO 体验。
  • 知道了,我会记住的。

标签: java string annotations character whitespace


【解决方案1】:

最简单的方法是使用正则表达式非数字字符类 (\D) 删除所有不是数字的内容:

test_id = test_id.replaceAll("\\D", "");

【讨论】:

  • 请注意输入a3c5e 将导致35。如果没问题,那么这是迄今为止最简单的解决方案。
  • 我正在做工程,对我来说是完美的解决方案。另外,@Andreas 我只想要数字字符,这很有效。
  • @PratikJaiswal 好。然后您应该通过单击复选标记来接受此答案。我只是在澄清效果,因此您可以睁大眼睛选择此选项。
【解决方案2】:

我强烈建议您调试您的方法。你会学到很多东西。

如果您在此处查看您的 if 声明:

if(Character.isLetter(test_id.trim().charAt(0))) {
    test_id = test_id.substring(1);
}

当您的test_id = "C1234" 时,您的条件为真。但是,您的问题变成了substring

回答:trim它!

test_id = test_id.trim().substring(1);

【讨论】:

  • 这也适用于我。调试了很多,当然也学到了很多。
猜你喜欢
  • 2011-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多