I couldnt find an answer for this in Java, so I'll ask here. I need to check if 3 parts of a string input contains a number (int).
The input will be HOURS:MINUTES:SECONDS (E.g. 10:40:50, which will be 10 hours, 40 minutes and 50 seconds). So far I am getting the values in String[] into an array by splitting it on :. I have parsed the strings into ints and I am using an if statement to check if all 3 parts is equal or larger than 0. The problem is that if I now use letters I will only just get an error, but I want to check if any of the 3 parts contains a character that is not 0-9, but dont know how.
First I thought something like this could work, but really dont.
String[] inputString = input.split(":");
if(inputString.length == 3) {
String[] alphabet = {"a","b","c"};
if(ArrayUtils.contains(alphabet,input)){
gives error message
}
int hoursInt = Integer.parseInt(inputString[0]);
int minutesInt = Integer.parseInt(inputString[1]);
int secondsInt = Integer.parseInt(inputString[2]);
else if(hoursInt >= 0 || minutesInt >= 0 || secondsInt >= 0) {
successfull
}
else {
gives error message
}
else {
gives error message
}
In the end I just want to check if any of the three parts contains a character, and if it doesnt, run something.
If you are sure you always have to parse a String of the form/pattern HH:mm:ss
(describing a time of day),
you can try to parse it to a LocalTime, which will only work if the parts HH, mm and ss are actually valid integers and valid time values.
Do it like this and maybe catch an Exception for a wrong input String:
public static void main(String[] arguments) {
String input = "10:40:50";
String wrongInput = "ab:cd:ef";
LocalTime time = LocalTime.parse(input);
System.out.println(time.format(DateTimeFormatter.ISO_LOCAL_TIME));
try {
LocalTime t = LocalTime.parse(wrongInput);
} catch (DateTimeParseException dtpE) {
System.err.println("Input not parseable...");
dtpE.printStackTrace();
}
}
The output of this minimal example is
10:40:50
Input not parseable...
java.time.format.DateTimeParseException: Text 'ab:cd:ef' could not be parsed at index 0
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalTime.parse(LocalTime.java:441)
at java.time.LocalTime.parse(LocalTime.java:426)
at de.os.prodefacto.StackoverflowDemo.main(StackoverflowDemo.java:120)
I would personally create my own helper methods for this, instead of using an external library such as Apache (unless you already plan on using the library elsewhere in the project).
Here is an example of what it could look like:
public static void main(String[] arguments) {
String time = "10:50:45";
String [] arr = time.split(":");
if (containsNumbers(arr)) {
System.out.println("Time contained a number!");
}
//You can put an else if you want something to happen when it is not a number
}
private static boolean containsNumbers(String[] arr) {
for (String s : arr) {
if (!isNumeric(s)) {
return false;
}
}
return true;
}
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(.\\d+)?");
}
containsNumbers will take a String array as an input and use an enhanced for loop to iterate through all the String values, using the other helper method isNumeric that checks if the String is a number or not using regex.
This code has the benefit of not being dependent on Exceptions to handle any of the logic.
You can also modify this code to use a String as a parameter instead of an array, and let it handle the split inside of the method instead of outside.
Note that typically there are better ways to work with date and time, but I thought I would answer your literal question.
Example Runs:
String time = "sd:fe:gbdf";
returns false
String time = "as:12:sda";
returns false
String time = "10:50:45";
returns true
You can check the stream of characters.
If the filter does not detect a non-digit, return "Numeric"
Otherwise, return "Not Numeric"
String str = "922029202s9202920290220";
String result = str.chars()
.filter(c -> !Character.isDigit(c))
.findFirst().isEmpty() ? "Numeric"
: "Not Numeric";
System.out.println(result);
If you want to check with nested loop you can see this proposal:
Scanner scanner = new Scanner(System.in);
String [] inputString = scanner.nextLine().split(":");
for (int i = 0; i < inputString.length; i++) {
String current = inputString[i];
for (int k = 0; k < current.length(); k++) {
if (!Character.isDigit(current.charAt(k))) {
System.out.println("Error");
break;
}
}
}
you could use String.matches method :
String notANum= "ok";
String aNum= "7";
if(notANum.matches("^[0-9]+$") sop("no way!");
if(aNum.matches("^[0-9]+$") sop("yes of course!");
The code above would print :
yes of course
The method accepts a regex, the one in the above exemple is for integers.
EDIT
I would use this instead :
if(input.matches("^\d+:\d+:\d+$")) success;
else error
You don't have to split the string.
I tried to make your code better, take a look. You can use Java regex to validate numbers. also defined range for time so no 24:61:61 values is allowed.
public class Regex {
static boolean range(int timeval,int min,int max)
{
boolean status=false;
if(timeval>=min && timeval<max)
{status=true;}
return status;
}
public static void main(String[] args) {
String regex = "[0-9]{1,2}";
String input ="23:59:59";
String msg="please enter valid time ";
String[] inputString = input.split(":");
if(inputString[0].matches(regex) && inputString[1].matches(regex) && inputString[2].matches(regex) )
{
if(Regex.range(Integer.parseInt(inputString[0]), 00, 24) &&Regex.range(Integer.parseInt(inputString[1]), 00, 60) && Regex.range(Integer.parseInt(inputString[2]), 00, 60))
{msg="converted time = " + Integer.parseInt(inputString[0]) + " : " +Integer.parseInt(inputString[1])+ " : " +Integer.parseInt(inputString[2]) ;}
}
System.out.println(msg);
}
}
Related
Do it exists a tool in Java to do this type of task below?
I got this hard typed String: {[1;3] || [7;9;10-13]}
The curly brackets {} means that is required
The square brackets [] means a group that is required
The double pipe || means a "OR"
Reading the string above, we get this:
It's required that SOME STRING have 1 AND 3 OR 7 AND 9 AND 10, 11, 12 AND 13
If true, it will pass. If false, will not pass.
I'm trying to do this in hard coding, but I'm felling that there is an easier or a RIGHT WAY to this type of validation.
Which type of content I must study to learn more about this?
I started with this code, but I'm felling that is not right:
//Gets the string
String requiredGroups = "{[1;3]||[7;9;10-13]}";
//Gets the groups that an Object belongs to
//It will return something like 5,7,9,10,11,12
List<Integer> groupsThatAnObjectIs = object.getListOfGroups();
//Validate if the Object is in the required groups
if ( DoTheObjectIsInRequiredGroups( groupsThatAnObjectIs, requiredGroups ) ) {
//Do something
}
I'm trying to use this iterator to get the required values from the requiredGroups variable
//Used for values like {[1;3]||[9;10;11-15]} and returns the required values
public static void IterateRequiredValues(String values, List<String> requiredItems) {
values = values.trim();
if( !values.equals("") && values.length() > 0 ) {
values = values.replace("{", "");
values = values.replace("}", "");
String arrayRequiredItems[];
if ( values.contains("||") ) {
arrayRequiredItems = values.split("||");
}
//NOTE: it's not done yet
}
}
So the rules are not really clear to me.
For example, are you only focussing on || or do you also have &&?
If I look at your example, I can derive from it that the && and operators are implicit in the ;.
None the less, I have made a code example (without much regex) that checks your rules.
First you need to begin with the || operator.
Put all the different OR statements into a String block.
Next you will need to check each element in the String block and check if the input value contains all block values.
If so then it must be true that your input string contains all the rules set by you.
If your rule consists of a range, you must first fully fill the range block
and then do the same with the range block as you would with the normal rule value.
Complete code example below.
package nl.stackoverflow.www.so;
import java.util.ArrayList;
import java.util.List;
public class App
{
private String rules = "{[1;3] || [7;9;10-13] || [34;32]}";
public static void main( String[] args )
{
new App();
}
public App() {
String[] values = {"11 12", "10 11 12 13", "1 2 3", "1 3", "32 23", "23 32 53 34"};
// Iterate over each value in String array
for (String value : values) {
if (isWithinRules(value)) {
System.out.println("Success: " + value);
}
}
}
private boolean isWithinRules(String inputValue) {
boolean result = false;
// || is a special char, so you need to escape it with \. and since \ is also a special char
// You need to escape the \ with another \ so \\| is valid for one | (pipe)
String[] orRules = rules.split("\\|\\|");
// Iterate over each or rules
for (String orRule : orRules) {
// Remove [] and {} from rules
orRule = orRule.replace("[", "");
orRule = orRule.replace("]", "");
orRule = orRule.replace("{", "");
orRule = orRule.replace("}", "");
orRule.trim();
// Split all and rules of or rule
String[] andRules = orRule.split(";");
boolean andRulesApply = true;
// Iterate over all and rules
for (String andRule : andRules) {
andRule = andRule.trim();
// check if andRule is range
if (andRule.contains("-")) {
String[] andRulesRange = andRule.split("-");
int beginRangeAndRule = Integer.parseInt(andRulesRange[0]);
int endRangeAndRule = Integer.parseInt(andRulesRange[1]);
List<String> andRangeRules = new ArrayList<String>();
// Add all values to another rule array
while (beginRangeAndRule < endRangeAndRule) {
andRangeRules.add(Integer.toString(beginRangeAndRule));
beginRangeAndRule++;
}
for (String andRangeRule : andRangeRules) {
// Check if andRule does not contain in String inputValue
if (!valueContainsRule(inputValue, andRangeRule)) {
andRulesApply = false;
break;
}
}
} else {
// Check if andRule does not contain in String inputValue
if (!valueContainsRule(inputValue, andRule)) {
andRulesApply = false;
break;
}
}
}
// If andRules apply, break and set bool to true because string contains all andRules
if (andRulesApply) {
result = true;
break;
}
}
return result;
}
private boolean valueContainsRule(String val, String rule) {
boolean result = true;
// Check if andRule does not contain in String inputValue
if (!val.contains(rule)) {
result = false;
}
return result;
}
}
I have seen other questions like this, but couldn't adapt any of the information to my code. Either because it wasn't specific to my issue or I couldn't get my head around the answer. So, I am hoping to ask "how" with my specific code. Tell me if more is needed.
I have various files (all jpg's) with names with the format "20140214-ddEventBlahBlah02.jpg" and "20150302-ddPsBlagBlag2".
I have a custom comparator in use that sorts things in a Windows OS fashion... i.e. 02,2,003,4,4b,4c,10, etc. Instead of the computer way of sorting, which was screwed up. Everything is good, except I now want to sort these strings using 2 criteria in the strings.
1) The date (in the beginning). i.e. 20150302
2) The rest of the filename after the "-" i.e. ddPsBlagBlag2
I am currently using the comparator for a project that displays these files in reverse order. They are displaying according to what was added most recently. i.e. 20150302 is displaying before 20140214. Which is good. But I would like the files, after being sorted by date in reverse order, to display by name in normal Windows OS ascending order (not in reverse).
Code:
Collections.sort(file, new Comparator<File>()
{
private final Comparator<String> NATURAL_SORT = new WindowsExplorerComparator();
#Override
public int compare(File o1, File o2)
{
return NATURAL_SORT.compare(o1.getName(), o2.getName());
}
});
Collections.reverse(file);
The code above takes the ArayList of file names and sends it to the custom WindowsExplorerComparator class. After being sorted, Collections.reverse() is called on the ArrayList.
Code:
class WindowsExplorerComparator implements Comparator<String>
{
private static final Pattern splitPattern = Pattern.compile("\\d\\.|\\s");
#Override
public int compare(String str1, String str2) {
Iterator<String> i1 = splitStringPreserveDelimiter(str1).iterator();
Iterator<String> i2 = splitStringPreserveDelimiter(str2).iterator();
while (true)
{
//Til here all is equal.
if (!i1.hasNext() && !i2.hasNext())
{
return 0;
}
//first has no more parts -> comes first
if (!i1.hasNext() && i2.hasNext())
{
return -1;
}
//first has more parts than i2 -> comes after
if (i1.hasNext() && !i2.hasNext())
{
return 1;
}
String data1 = i1.next();
String data2 = i2.next();
int result;
try
{
//If both datas are numbers, then compare numbers
result = Long.compare(Long.valueOf(data1), Long.valueOf(data2));
//If numbers are equal than longer comes first
if (result == 0)
{
result = -Integer.compare(data1.length(), data2.length());
}
}
catch (NumberFormatException ex)
{
//compare text case insensitive
result = data1.compareToIgnoreCase(data2);
}
if (result != 0) {
return result;
}
}
}
private List<String> splitStringPreserveDelimiter(String str) {
Matcher matcher = splitPattern.matcher(str);
List<String> list = new ArrayList<String>();
int pos = 0;
while (matcher.find()) {
list.add(str.substring(pos, matcher.start()));
list.add(matcher.group());
pos = matcher.end();
}
list.add(str.substring(pos));
return list;
}
}
The code above is the custom WindowsExplorerComperator class being used to sort the ArrayList.
So, an example of what I would like the ArrayList to look like after being sorted (and date sort reversed) is:
20150424-ssEventBlagV002.jpg
20150323-ssEventBlagV2.jpg
20150323-ssEventBlagV3.jpg
20150323-ssEventBlagV10.jpg
20141201-ssEventZoolander.jpg
20141102-ssEventApple1.jpg
As you can see, first sorted by date (and reversed), then sorted in ascending order by the rest of the string name.
Is this possible? Please tell me its an easy fix.
Your close, whenever dealing with something not working debug your program and make sure that methods are returning what you would expect. When I ran your program first thing I noticed was that EVERY compare iteration which attempted to convert a string to Long threw a NumberFormatException. This was a big red flag so I threw in some printlns to check what the value of data1 and data2 were.
Heres my output:
Compare: 20150323-ssEventBlagV 20150424-ssEventBlagV00
Compare: 20150323-ssEventBlagV 20150323-ssEventBlagV
Compare: 3. 2.
Compare: 20150323-ssEventBlagV 20150424-ssEventBlagV00
Compare: 20150323-ssEventBlagV 20150323-ssEventBlagV
Compare: 3. 2.
Compare: 20150323-ssEventBlagV1 20150323-ssEventBlagV
Compare: 20150323-ssEventBlagV1 20150424-ssEventBlagV00
Compare: 20141201-ssEventZoolander.jpg 20150323-ssEventBlagV1
Compare: 20141201-ssEventZoolander.jpg 20150323-ssEventBlagV
Compare: 20141201-ssEventZoolander.jpg 20150323-ssEventBlagV
Big thing to notice here is that its trying to convert 3. and 2. to long values which of course wont work.
The simplest solution with your code is to simply change your regular expression. Although you might go for a more simple route of string iteration instead of regex in the future, I feel as though regex complicates this problem more than it helps.
New regex: \\d+(?=\\.)|\\s
Changes:
\\d -> \\d+ - Capture all digits before the period not just the first one
\\. -> (?=\\.) - place period in non capturing group so your method doesn't append it to our digits
New debug output:
Compare: 20150323-ssEventBlagV 20150424-ssEventBlagV
Compare: 20150323-ssEventBlagV 20150323-ssEventBlagV
Compare: 3 2
Compare: 20150323-ssEventBlagV 20150323-ssEventBlagV
Compare: 10 3
Compare: 20141201-ssEventZoolander.jpg 20150323-ssEventBlagV
As you can see the numbers at the end are actually getting parsed correctly.
One more minor thing:
Your result for digit comparison is backwards
result = Long.compare(Long.valueOf(data1), Long.valueOf(data2));
should be either:
result = -Long.compare(Long.valueOf(data1), Long.valueOf(data2));
or
result = Long.compare(Long.valueOf(data2), Long.valueOf(data1));
because its sorting them backwards.
There are a few things you should do:
First, you need to fix your split expression as #ug_ stated. However, I think splitting on numbers is more appropriate.
private static final Pattern splitPattern = Pattern.compile("\\d+");
which, for 20150323-ssEventBlagV2.jpg will result in
[, 20150323, -ssEventBlagV, 2, .jpg]
Second, perform a date comparison separate from your Long comparison. Using SimpleDateFormat will make sure you are only comparing numbers that are formatted as dates.
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
result = sdf.parse(data2).compareTo(sdf.parse(data1));
if (result != 0) {
return result;
}
} catch (final ParseException e) {
/* continue */
}
Last, swap the order of your Long compare
Long.compare(Long.valueOf(data2), Long.valueOf(data1));
And you should be good to go. Full code below.
private static final Pattern splitPattern = Pattern.compile("\\d+");
#Override
public int compare(String str1, String str2) {
Iterator<String> i1 = splitStringPreserveDelimiter(str1).iterator();
Iterator<String> i2 = splitStringPreserveDelimiter(str2).iterator();
while (true) {
// Til here all is equal.
if (!i1.hasNext() && !i2.hasNext()) {
return 0;
}
// first has no more parts -> comes first
if (!i1.hasNext() && i2.hasNext()) {
return -1;
}
// first has more parts than i2 -> comes after
if (i1.hasNext() && !i2.hasNext()) {
return 1;
}
String data1 = i1.next();
String data2 = i2.next();
int result;
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
result = sdf.parse(data1).compareTo(sdf.parse(data2));
if (result != 0) {
return result;
}
} catch (final ParseException e) {
/* continue */
}
try {
// If both datas are numbers, then compare numbers
result = Long.compare(Long.valueOf(data2),
Long.valueOf(data1));
// If numbers are equal than longer comes first
if (result == 0) {
result = -Integer.compare(data1.length(),
data2.length());
}
} catch (NumberFormatException ex) {
// compare text case insensitive
result = data1.compareToIgnoreCase(data2);
}
if (result != 0) {
return result;
}
}
}
You will need to edit your WindowsExporerComparator Class so that it performs this sorting. Given two file names as Strings you need to determine what order they go in using a following high level algorithm.
are they the same? if yes return 0
Split the file name into two strings, the date portion and the name portion.
Using the date portion convert the string to a date using the Java DateTime and then compare the dates.
If the dates are the same compare the two name portions using your current compare code and return the result from that.
This is a bit complicated and sort of confusing, but you will have to do it in one comparator and put in all of your custom logic
May I know how can I remove the leading zero in JAVA code? I tried several methods like regex tools
"s.replaceFirst("^0+(?!$)", "") / replaceAll("^0*", "");`
but it's seem like not support with my current compiler compliance level (1.3), will have a red line stated the method replaceFirst(String,String)is undefined for the type String.
Part of My Java code
public String proc_MODEL(Element recElement)
{
String SEAT = "";
try
{
SEAT = setNullToString(recElement.getChildText("SEAT")); // xml value =0000500
if (SEAT.length()>0)
{
SEAT = SEAT.replaceFirst("^0*", ""); //I need to remove leading zero to only 500
}
catch (Exception e)
{
e.printStackTrace();
return "501 Exception in proc_MODEL";
}
}
}
Appreciate for help.
If you want remove leading zeros, you could parse to an Integer and convert back to a String with one line like
String seat = "001";// setNullToString(recElement.getChildText("SEAT"));
seat = Integer.valueOf(seat).toString();
System.out.println(seat);
Output is
1
Of course if you intend to use the value it's probably better to keep the int
int s = Integer.parseInt(seat);
System.out.println(s);
replaceFirst() was introduced in 1.4 and your compiler pre-dates that.
One possibility is to use something like:
public class testprog {
public static void main(String[] args) {
String s = "0001000";
while ((s.length() > 1) && (s.charAt(0) == '0'))
s = s.substring(1);
System.out.println(s);
}
}
It's not the most efficient code in the world but it'll get the job done.
A more efficient segment without unnecessary string creation could be:
public class testprog {
public static void main(String[] args) {
String s = "0001000";
int pos = 0;
int len = s.length();
while ((pos < len-1) && (s.charAt(pos) == '0'))
pos++;
s = s.substring(pos);
System.out.println(s);
}
}
Both of those also handle the degenerate cases of an empty string and a string containing only 0 characters.
Using a java method str.replaceAll("^0+(?!$)", "") would be simple;
First parameter:regex -- the regular expression to which this string is to be matched.
Second parameter: replacement -- the string which would replace matched expression.
As stated in Java documentation, 'replaceFirst' only started existing since Java 1.4 http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceFirst(java.lang.String,%20java.lang.String)
Use this function instead:
String removeLeadingZeros(String str) {
while (str.indexOf("0")==0)
str = str.substring(1);
return str;
}
I have 2 strings "test" "bet" and another string a="tbtetse". I need to check if the "tbtetse" contains the other two strings.
I was thinking if I could find all the anagrams of string a and and then find the other two strings in those, but it doesn't work that way and also my anagram code is failing for a lengthy string.
Could you please help with any other ways to solve it?
Assuming you're trying to test whether the letters in a can be used to form an anagram of the test strings test and bet: I recommend making a dictionary (HashMap or whatever) of character counts from string a, indexed by character. Build a similar dictionary for the words you're testing. Then make sure that a has at least as many instances of each character from the test strings as they have.
Edit: Alcanzar suggests arrays of length 26 for holding the counts (one slot for each letter). Assuming you're dealing with only English letters, that is probably less of a hassle than dictionaries. If you don't know the number of allowed characters, the dictionary route is necessary.
Check below code, it may help you.
public class StringTest {
public static void main(String[] args) {
String str1 = "test";
String str2 = "bev";
String str3 = "tbtetse";
System.out.println(isStringPresent(str1, str2, str3));
}
private static boolean isStringPresent(String str1, String str2, String str3) {
if ((str1.length() + str2.length()) != str3.length()) {
return false;
} else {
String[] str1Arr = str1.split("");
String[] str2Arr = str2.split("");
for (String string : str1Arr) {
if (!str3.contains(string)) {
return false;
}
}
for (String string : str2Arr) {
if (!str3.contains(string)) {
return false;
}
}
}
return true;
}
}
basically you need to count characters in both sets and compare them
void fillInCharCounts(String word,int[] counts) {
for (int i = 0; i<word.length(); i++) {
char ch = word.charAt(i);
int index = ch - 'a';
counts[index]++;
}
}
int[] counts1 = new int[26];
int[] counts2 = new int[26];
fillInCharCounts("test",counts1);
fillInCharCounts("bet",counts1);
fillInCharCounts("tbtese",counts2);
boolean failed = false;
for (int i = 0; i<counts1.length; i++) {
if (counts1[i] > counts2[i]) {
failed = true;
}
}
if (failed) {
whatever
} else {
something else
}
If you are generalizing it, don't forget to call .toLowerCase() on the word before sending it in (or fix the counting method).
Pseudo code:
Make a copy of string "tbtetse".
Loop through each character in "test".
Do a indexOf() search for the character in your copied string and remove it if found.
If not found, fail.
Do the same for the string "bet".
class WordLetter {
char letter;
int nth; // Occurrence of that letter
...
}
One now can use Sets
Set<WordLetter>
// "test" = { t0 e0 s0 t1 }
Then testing reduces to set operations. If both words need to be present, a union can be tested. If both words must be formed from separate letters, a set of the concatenation can be tested.
I have a string (comma seperated)
For example:
a,bgf,sad,asd,rfw,fd,se,sdf,sdf,...
What I need is to extract a substring up to the 1000th comma.
How to achieve this in Java?
An efficient way of doing this would be to use indexof(int ch, int fromIndex) intead of using split(String regex, int limit) or split(String regex) especially if the given string is long.
This could be done something like this
[pseudocode]
asciiCodeForComma = 0x2c
nextIndex=0
loop 1000 times
nextIndex= csv.indexof(asciiCodeForComma , nextIndex)
requiredSubString = csv.subString(0, nextIndex)
String csv = "some,large,string";
String[] parts = csv.split(",");
String thousandthElement = null; // the default value if there are less than 1000
if (parts.length > 999)
thousandthElement = parts[999];
You can use StringTokenizer with comma as separator, then loop nextToken() 1000 times.
I think he is asking for all 1000 element.. This should solve your problem. Understand and then copy-paste as this is ur homework :)
public static void main(String[] args) {
// TODO Auto-generated method stub
String samplecsv = "a,bgf,sad,asd,rfw,fd,se,sdf,sdf,";
String[] splitedText = samplecsv.split(",");
StringBuffer newtext = new StringBuffer();
for (int i = 0; i < 3; i++) {
newtext.append(splitedText[i]);
}
System.out.println(newtext);
}
So to solve this problem what you need to do is understand how to extract a string from a delimiter separated input stream. Then executing this for the case for N strings is trivial. The pseudocode for doing this for the individual record is below:
function parse(inputValue, delimiter)
{
return inputValue.split(delimiter)
}
Now to do that for the case where there are N inputValues is equally as trivial.
function parse(inputValues, delimiter)
{
foreach inputValue in inputValues
returnValue.append(parse(inputValue,delimiter)
return returnValue
}
There is actually built in functionality to do this by putting a second argument into split. If what you're really looking for is the whole string before the 1000th comma, you can still use this function but you will have to concatenate the first section of the array.
public static void main(String[] args){
String sample = "s,a,m,p,l,e";
String[] splitSample = sample.split(",",1000);
if (splitSample.length == 1000)
System.out.println(splitSample[1000]);
else
System.out.println("Your error string");
}