In this article we will see how to split string in Java both by using String’s split() method and StringTokenizer. If you have any doubt on anything related to split string please let me know and I will try to help.
String Split Example JavaLet's see an example of splitting string in Java by using split() function:
OutPutsplits.size: 5GoldStocksFixed IncomeCommodityInterest Rates
In above example we have provided delimiter or separator as “:” to split function which expects a regular expression and used to split the string.Now let see another example of split using StringTokenizer
OutPutGoldStocksFixed IncomeCommodityInterest Rates
My personal favorite is String.split () because it’s defined in String class itself and its capability to handle regular expression which gives you immense power to split the string on any delimiter you ever need. Though it’s worth to remember following points about split method in Java
1) Some special characters need to be escaped while using them as delimiters or separators e.g. "." and "|".
OutPut:Gold TradingStocks TradingFixed Income TradingCommodity TradingFX trading
OutPut:Apple IPhoneHTC Evo3DNokia N9LG OptimusSony XperiaSamsung Charge2) You can control number of split by using overloaded version split (regex, limit). If you give limit as 2 it will only creates two strings. For example in following example we could have total 4 splits but if we just want to create 2 we can use limit.
Output:placeSplits.size: 2LondonSwitzerland.Europe.AustraliaTo conclude the topic StringTokenizer is old way of tokenizing string and with introduction of split since JDK 1.4 its usage is discouraged. No matter what kind of project you work you often need to split string in Java so better get familiar with these API.
Copyright @ Eric_jiang Powered by: .Text and ASP.NET Theme by: .NET Monster