字符串函数如何计算字符串行中的分隔符 [英] String Functions how to count delimiter in string line

查看:60
本文介绍了字符串函数如何计算字符串行中的分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的字符串行如下:

A:B:C:D:E:F:G:H:I:J:K:L:M

A:B:C:D:E:F:G:H:I:J:K:L:M

这意味着定界符(:)计数为12.这行是有效的.

It means delimiter ( : ) count is 12 . This line is valid.

现在假设您有以下一行:

Now suppose you have a following line :

A:B:C:D:E:F:G:H :::::

A:B:C:D:E:F:G:H:::::

这行也是有效的,因为它包含12个定界符.其中存在8个值,其中4个值为空白.

This line is also valid because it contains 12 delimiter . where 8 values are present and 4 values are blank.

现在以下行应无效:

A:B:C:D:E:F:-无效-因为它仅包含6个值,但预期为12个.

A:B:C:D:E:F: -- Invalid - because it contains only 6 values but expected are 12.

该怎么做..?我尝试了以下代码,但未获得所需的输出:

how to do this .. ? I tried the following code , but not getting the desired output :

String strLine = "A:B:C:D:E:F:G:H:::::" ;
int delimiterCount = 12 ; 

String[] ValuesArray = strLine.split(":");
 if(ValuesArray.length != delimiterCounter){
 System.out.println(Invalid);
 }else {
 System.out.println("ValidLine");
 }

我将输出视为无效,因为它应该是有效的.

I am getting the output as Invalid where as it sould be Valid.

推荐答案

如果您想使用 split ,并且它的确不是一个坏方法(尽管可能适用于这种特殊情况),需要将-1作为第二个参数传递给 split ,否则它将删除空字符串.

If you want to use split, and it's not a bad approach really (although it might be for this particular situation), you need to pass -1 as the second argument to split otherwise it removes empty strings.

请参见 http://ideone.com/gaUw5 .

很高兴知道有关 split 的知识.有些语言要求-1,有些则不需要.

It is good to know this about split. Some languages require the -1 and some do not.

代码

class Main {
    public static void main(String[] args) {
        String line = "A:B:C:D:E:F:G:H:::::" ;
        int delimiterCount = 12 ; 

        String[] values = line.split(":", -1);
        if (values.length != delimiterCount + 1) {
            System.out.println("Invalid Line");
        } else {
            System.out.println("Valid Line");
        }
    }
}

这篇关于字符串函数如何计算字符串行中的分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆