简体   繁体   English

如何在Java中使用子字符串方法

[英]How to use the substring method in Java

I have 3 strings: 我有3个字符串:

String text1 = "abcdefgh";
String text2 = "abcdefghijklmn";
String text3 = "abcdefg";

and i want to do something like this: 我想做这样的事情:

text1.substring(int1, int2);
text2.substring(int1, int2);
text3.substring(int1, int2);

that would return abc(the first 3 characters) the problem is that the strings length is always changing, so i can't use text1.length no matter what. 那会返回abc(前3个字符)的问题是字符串的长度总是在变化,所以无论如何我都不能使用text1.length。

If the length is changing, do a check first 如果长度有所变化,请先进行检查

if (textStr != null && textStr.length() >= 3) {
    newStr = textStr.substring(0, 3);
}

找到了答案:

.substring(0, 3)

Because the string length can vary (or perhaps even be null) you'd be better off writing something a little more general purpose. 因为字符串的长度可以变化(或者甚至可以为null),所以最好写一些更通用的东西。 In your example your test strings are always longer than 3 characters, but is that always the case? 在您的示例中,测试字符串始终长于3个字符,但情况总是这样吗? You could also write this function to automatically pad the string to your desired length. 您也可以编写此功能以自动将字符串填充到所需的长度。

public static String variableLengthSubstring(String text, int length) {
    StringBuilder substring = new StringBuilder();
    if(text != null) {
        int i = 0;
        length = Math.min(length, text.length());
        while(substring.length() < length) {
            substring.append(text.charAt(i++));
        }
    }
    return substring.toString();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM