Reputation: 653
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.
Upvotes: 1
Views: 85
Reputation: 1251
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.
static String getArgs(String command, int argumentIndex) {
int start = 0;
int end = -1;
for (int i = 0; i <= argumentIndex; i++) {
start = command.indexOf("\"", end+1)+1;
end = command.indexOf("\"", start+1);
if (i == argumentIndex) {
return command.substring(start, end);
}
}
return null;
}
Try this for a more generic solution which accepts arguments without quotes also
static String getArgs(String command, int argumentIndex) {
int start = 0;
int end = -1;
String delimiter = " ";
for (int i = 0; i <= argumentIndex && !command.equals(""); i++) {
if (command.startsWith("\"")) {
delimiter = "\"";
start = 1;
} else {
delimiter = " ";
start = 0;
}
end = command.indexOf(delimiter, start+1);
if (i == argumentIndex) {
end = (end==-1?command.length():end);
return command.substring(start, end).trim();
} else {
end = (end==-1?command.length():end+1);
command = command.substring(end).trim();
}
}
return null;
}
Upvotes: 0
Reputation: 654
@Darestium
According to your string it is clear that you've an empty space in between your paths. And also you've a problem with empty space.
To make it simple just split the string with space and the use the last 2 in the output.
Use `split(String arg)` in your case it is
String[] words=YOUR_STRING.split(" ");
for(int i=0;i<llength;i++)
{ if(words[i].startsWith("\"") && words[i].endsWith("\"")
{
word[i];YOUR DESIRED OUTPUT
}
}
Upvotes: 1