How to Split a String in Java
In earlier topics, we have seen how we joined/concatenated strings, similarly we may also need to break some string based on some attributes. Mainly this attribute will be something like a separator or a common pattern with which you want to break or split the string. The StrSplit() method splits a String into an array of substrings given a specific delimiter. Let’s consider an example here: Suppose we have a string variable named strMain formed of a few words like Alpha, Beta, Gamma, Delta, Sigma – all separated by comma (,). Here if we want all individual strings, the best possible pattern would be to split it based on comma. So we will get 5 separate strings as follows: Alpha Beta Gamma Delta Sigma How to Split a String in Java Use the split method against the string that needs to be divided and provide the separator as argument. Java split string into array - StrSplit() In this case, the separator is comma (,) and the result of the split operation will give you an array split . class StrSplit{ public static void main(String []args){ String strMain = "Alpha, Beta, Delta, Gamma, Sigma"; String[] arrSplit = strMain.split(", "); for (int i=0; i< arrSplit.length; i++) { System.out.println(arrSplit[i]); } } } The loop in the code just prints each string (element of array) after the split operation, as shown below- Alpha Beta Delta Gamma Sigma Consider a situation, wherein you require only the first ‘n’ elements after the split operation but want the rest of the string remain as it is. An output something like this- Alpha Beta Delta, Gamma, Sigma This can be achieved by passing another argument along with the split operation and that will be the limit of strings required. Actually, it is the 1 greater than the number of times the string will be split into. See the following code – class StrSplit2{ public static void main(String []args){ String strMain = "Alpha, Beta, Delta, Gamma, Sigma"; String[] arrSplit_2 = strMain.split(", ", 3); for (int i=0; i< arrSplit_2.length; i++){ System.out.println(arrSplit_2[i]); } } }

0 Comments

'; (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })();