I have written a function in my program that allows me to retrieve strings and a separate string. ie, the string:
‘copy “C:\Users\USERNAME\Desktop\file.bat” “C:\Users\”‘
would result in having a string like: ‘C:\Users\USERNAME\Desktop\file.bat’ with the function getArgs(command, 0), and the other ‘C:\Users\’ with the function getArgs(command, 1).
The problem is that the function always seems to retrieve an empty string. Please be lenient on me, this is my first time using string manipulation functions in Java.
Notice: When I say empty I do not mean NULL, I mean “”.
static String getArgs(String command, int argumentIndex) {
int start = 0;
int end = 0;
for (int i = 0; i <= argumentIndex; i++) {
start = command.indexOf("\"", end);
end = command.indexOf("\"", start);
if (i == argumentIndex) {
return command.substring(start, end);
}
}
return null;
}
Any ideas? Thanks.
Try the following correction. Keep in mind that your solution while work only if all the arguments in the command string are wrapped in quotes, even the ones without spaces. In the example you provided the first argument (‘copy’) must be also wrapped in quotes since you are using the quotes as delimiters.
Try this for a more generic solution which accepts arguments without quotes also