Java字符串拆分多个空格

Java中常见的编程方案是使用空格作为分隔符来拆分字符串。例如,当我们要检索文本文档中的所有单词时,这很有用。空格是分隔每个单词的标记。 拆分功能非常强大,因为您可以通过正则表达式指定分隔符。由于正则表达式的功能,它可以节省很多时间。
 

 

按单个空格分割

 

如果我们有字符串“ Apple Banana Carrot”,我们可以看到有3个单词,用单个空格分隔。这是有关如何分割字符串和检索单词的示例代码:

public class TestConsole {
   public static void main(String[] args) {
      String sampleString = "Apple Banana Carrot";
      String[] animals = sampleString.split(" ");
      int animalIndex = 1;
      for (String animal : animals) {
         System.out.println(animalIndex + ". " + animal);
         animalIndex++;
      }
   }

注意,我们在逻辑中合并了一个计数器,以便清楚地发现有多少令牌。输出如下所示。

1. Apple
2. Banana
3. Carrot

 

在这种情况下,动物数组包含三个项目。

 

按多个空格/空格分隔

 

制表符,空格和换行符通常称为空白。在正则表达式中,\ s表示空格。一个或多个空格的序列可以表示为\ s +。在Java中使用时,只需要使用\即可。这是解析由多个空格分隔的String的示例代码:

public class TestConsole {
   public static void main(String[] args) {
      String sampleString = "Cat  Dog    Elephant     Fox";
      String[] animals = sampleString.split("\\s+");
      int animalIndex = 1;
      for (String animal : animals) {
         System.out.println(animalIndex + ". " + animal);
         animalIndex++;
      }
   }
}

这是示例输出。请注意,正确识别了这四个项目。

1. Cat
2. Dog
3. Elephant
4. Fox

 

这是修改后的示例,该示例分析包含制表符和换行符的字符串:

public class TestConsole {
   public static void main(String[] args) {
      String sampleString = "Cat    Dog \t Elephant \n Fox \r\n Goat";
      String[] animals = sampleString.split("\\s+");
      int animalIndex = 1;
      for (String animal : animals) {
         System.out.println(animalIndex + ". " + animal);
         animalIndex++;
      }
   }
}

并且输出仍然符合预期。

1. Cat
2. Dog
3. Elephant
4. Fox
5. Goat

 

在这种情况下,动物数组包含五个项目。

 

按单个空格/空格分隔

 

尽管很少见,但有时我们只想将一个字符串分割成一个空格。这是一个例子

public class TestConsole {
   public static void main(String[] args) {
      String sampleString = "Cat  Dog    Elephant     Fox";
      String[] animals = sampleString.split("\\s");
      int animalIndex = 1;
      for (String animal : animals) {
         System.out.println(animalIndex + ". " + animal);
         animalIndex++;
      }
   }
}

这是示例输出。请注意,每个连续的空格将在结果数组中导致一个空的String项。

1. Cat
2. 
3. Dog
4. 
5. 
6. 
7. Elephant
8. 
9. 
10. 
11. 
12. Fox

 

在这种情况下,动物数组包含十二个项目,其中eigth是空字符串。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值