7

I have this piece of code in my java class

mystring  = mysuperstring.split("/");

I want to know how many sub-string is created from the split.

In normal situation, if i want to access the first sub-string i just write

mystring[0];

Also, i want to know if mystring[5] exist or not.

sameer
  • 220
  • 2
  • 6
  • 18

6 Answers6

16

I want to know how many sub-string is created from the split.

Since mystring is an array, you can simply use mystring.length to get the number of substrings.

Also, i want to know if mystring[5] exist or not.

To do this:

if (mystring.length >= 6) { ... }
NPE
  • 486,780
  • 108
  • 951
  • 1,012
10
mystring  = mysuperstring.split("/");
int size = mystring.length;

remember that arrays are zero indexed, so where length = 5, the last element will be indexed with 4.

NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
3

It's a simple way to count the sub-strings

word.split('/').length;

You can see an example of this implementation here.

li_developer
  • 139
  • 1
  • 2
0

I wanted to demo a dumy token validation. So I tried to split by dot (.). It did not worked. So, I wonder and checked out an hour with no luck. After a while, when randomly trying I added escape character before dot and thank god it worked :D.

The reason is split takes string as regex. I checked why when writing an answer here:

You are splitting on the regex ., which means "any character"

int len = accessToken.split("\\.").length;

String I wanted to check

String accessToken = Bearer 1111.1111.11111 // demonstration purpose dumy

Output:

3
Blasanka
  • 21,001
  • 12
  • 102
  • 104
0

Try this one & tell me if it works.

import java.util.regex.Pattern;

public class CountSubstring {
    public static int countSubstring(String subStr, String str){
        // the result of split() will contain one more element than the delimiter
        // the "-1" second argument makes it not discard trailing empty strings
        return str.split(Pattern.quote(subStr), -1).length - 1;
    }

    public static void main(String[] args){
        System.out.println(countSubstring("th", "the three truths"));
        System.out.println(countSubstring("abab", "ababababab"));
        System.out.println(countSubstring("a*b", "abaabba*bbaba*bbab"));
    }
}
Java
  • 2,451
  • 10
  • 48
  • 85
0

I think you must read about split and array, please find the links.

if you read about split function it returns Array of String.

and now you should read about Array and its size

dku.rajkumar
  • 18,414
  • 7
  • 41
  • 58