Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of sub string from a split in java

Tags:

java

string

split

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.

like image 828
sameer Avatar asked Feb 29 '12 13:02

sameer


People also ask

How do you find the number of substrings?

Total number of substrings = n + (n - 1) + (n - 2) + (n - 3) + (n - 4) + ……. + 2 + 1. So now we have a formula for evaluating the number of substrings where n is the length of a given string.

How many substrings are there in a string of length n?

Approach: The count of sub-strings of length n will always be len – n + 1 where len is the length of the given string.


3 Answers

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) { ... }
like image 57
NPE Avatar answered Oct 05 '22 01:10

NPE


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.

like image 21
NimChimpsky Avatar answered Oct 05 '22 02:10

NimChimpsky


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

word.split('/').length;

You can see an example of this implementation here.

like image 43
li_developer Avatar answered Oct 05 '22 00:10

li_developer