About Java input string filter - java

I have a very simple question about JAVA string filter
I to want input this command to console.
add 100#10
which means execute add method input arguments 100 and 10 respectively.
I used
String[] s = str.split("#");
String a = s[0];// here can get 100
String b=s1];// get can get 10
I have two questions
first is how to do delete the at (#) character before put it to string.split()
second can anyone can provide some better solution to handle this kind of input ?
such as
add 1000#10 //only add,1000,10 need to take
times 1000#10 //only add,1000,10 need to take

You can split on multiple tokens because it's a regex parameter:
String a[] = "aadd 100#200".split("[ #]");
returns ["aadd", "100", "200"]
Then you can do
String command = a[0];
String operand1 = a[1];
String operand2 = a[2];

not as sexy as ergonaut's solution, but you also can use two splits:
String[] arr1 = "add 100#10".split(" ");
String[] arr2 = arr1[1].split("#");
String[] result = [arr1[0], arr2[0], arr2[1]];
should be
["add","100","10"]; // this is result
greetings

Related

How to split a string by a newline and a fixed number of tabs like "\n\t" in Java?

My input string is the following:
String input = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext";
My intended result is
dir,
subdir1,
subdir2\n\t\tfile.ext
The requirement is to split the input by "\n\t" but not "\n\t\t".
A simple try of
String[] answers = input.split("\n\t");
also splits "\tfile.ext" from the last entry. Is there a simple regular expression to solve the problem? Thanks!
You can split on a newline and tab, and assert not a tab after it to the right.
\n\t(?!\t)
See a regex demo.
String input = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext";
String[] answers = input.split("\\n\\t(?!\\t)");
System.out.println(Arrays.toString(answers));
Output
[dir, subdir1, subdir2
file.ext]
If you are looking for a generic approach, it highly depends on what format will input generally have. If your format is static for all possible inputs (dir\n\tdir2\n\tdir3\n\t\tfile.something) one way to do it is the following:
String input = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext";
String[] answers = input.split("\n\t");
for (int i = 1; i < answers.length; i++)
if (answers[i].contains("\t"))
answers[i-1] = answers[i-1] + "\n\t" + answers[i];
String[] answersFinal = Arrays.copyOf(answers, answers.length-1);
for (int i = 0; i < answersFinal.length; i++)
answersFinal[i] = answers[i];
for (String s : answersFinal)
System.out.println(s);
However this is not a good solution and I would suggest reformatting your input to include a special sequence of characters that you can use to split the input, for example:
String input = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext";
input = input.replaceAll("\n\t", "%%%").replaceAll("%%%\t", "\n\t\t");
And then split the input with '%%%', you will get your desired output.
But again, this highly depends on how generic you want it to be, the best solution is to use an overall different approach to achieve what you want, but I cannot provide it since I don't have enough information on what you are developing.
You can simply do:
String input = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext";
String[] modifiedInput = input.replaceAll("\n\t\t", "####").replaceAll("\n\t", "§§§§").replaceAll("####", "\n\t\t").split("§§§§");
Replace each \n\t\t which contain the \n\t
Replace each \n\t
Change back the \n\t\t as you seemingly want to preserve it
Make the split.
Not very efficient but still works fast enough if you won't use it in mass data situations.
This approach is more efficient as it only uses 2 splits but only works if there is only one element prefixed with \n\t\t at the end. Accessing an Array is kind of cheap O(1) so constant time. More code but less full iterations (replaceAll, split).
final String input = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext";
final String[] s1 = input.split("\n\t\t");
final String last = s1[s1.length - 1];
final String[] modifiedInput = s1[0].split("\n\t");
modifiedInput[modifiedInput.length -1] = modifiedInput[modifiedInput.length -1] + "\n\t\t" + last;

Extracting specific parts of a String

I am trying to get the "work" part of this string:
String test = "\prod\mp\incoming\users\work\test.java";
I have been trying to do it this way:
String result = test.substring(test.lastIndexOf("\\")+1 , test.length());
But this is returning "test.java"
try:
String test = "\\prod\\mp\\incoming\\users\\work\\test.java";
String[] s = test.split("\\");
result = s[s.length-2];
Here is the split method signature:
public String[] split(String regex);
It splits this string around matches of the given regular expression and returns an array of String containing the matches. In your case you need to get the second to last match which is the the match with index s.length-2 since the last element in the array s has the index s.length-1
Break your one-liners down into sensible parts. Instead of this...
String result = test.substring(test.lastIndexOf("\\") + 1 , test.length());
... try this...
int lastSlashIndex = test.lastIndexOf("\\");
int endIndex = test.length();
String result = test.substring(lastSlashIndex + 1, endIndex);
It then becomes painfully obvious that your substring goes from the last slash to the end of the string. So how do you fix it? First, you need to describe the problem properly. There are two possible things you are trying to do, and I have no idea which is correct:
You want to find the fifth item in the path.
You want to find the second to last item in the path.
I'll tackle the first, and if it turns out to be the second, you should be able to follow what I've done and do it yourself.
// Get the fifth item in the path
String[] items = test.split("\\");
String result = items[4];
Add some error checking to prevent an array index out of bounds exception.
String[] items = test.split("\\");
String result = "";
if (items.length > 4)
result = items[4];

input string to int from command line in java

I am writing a program in Java that makes use of the command line.
The program that I'm making is used by another program, the problem is that my 4th parameter has to be an int, for example 60(this is an int, it's used for calculations) for my program to work, and the program that uses it then has fixedwidth:60(this is a string) as the 4th parameter.
My question now is how is it possible to still use the 60 in calculations while not giving errors due to the program using it having a string as a 4th parameter and not an int. I have triend Integer.parseInt and Integer.ToString, but I still get the same error
Thanks in advance.
Split the string on : and then parse the second part, like so -
String str = "fixedwidth:60";
String[] arr = str.split(":");
int val = Integer.parseInt(arr[1]);
// OR -
// int val = Integer.valueOf(arr[1]);
System.out.println(val);
Output is
60
Integer.parseInt(String) and Integer.valueOf(String) both expect the input String to be just the number you want to parse. That's why you probably get a NumberFormatException when trying to parse "fixedwidth:60".
If you really need to input the whole string "fixedwidth:60", you must first extract the number from that string. You can do that with Elliott Frisch's code using String.split(":"):
String str = "fixedwidth:60";
String[] arr = str.split(":"); // arr = { "fixedwidth", "60"}
int val = Integer.parseInt(arr[1]); // arr[1] = "60", which can be parsed

How to extract specific letters in string with java

I have some expression in a Java string and a would get the letter, which was on the left side and on the right side of a specific sign.
Here are two examples:
X-Y
X-V-Y
Now, I need to extract in the first example the letter X and Y in a separate string. And in the second example, I need to extract the letters X, V and Y in a separate string.
How can i implemented this requirement in Java?
Try with:
String input = "X-V-Y";
String[] output = input.split("-"); // array with: "X", "V", "Y"
use String.split method with "-" token
String input = "X-Y-V"
String[] output = input.split("-");
now in the output array there will be 3 elements X,Y,V
String[] results = string.split("-");
do like this
String input ="X-V-Y";
String[] arr=input.split("-");
output
arr[0]-->X
arr[1]-->V
arr[2]-->Y
I'm getting in on this too!
String[] terms = str.split("\\W"); // split on non-word chars
You can use this method :
public String[] splitWordWithHyphen(String input) {
return input.split("-");
}
you can extract and handle a string by using the following code:
String input = "x-v-y";
String[] extractedInput = intput.split("-");
for (int i = 0; i < extractedInput.length - 1; i++) {
System.out.print(exctractedInput[i]);
}
Output: xvy

Split()-ing in java

So let's say I have:
String string1 = "123,234,345,456,567*nonImportantData";
String[] stringArray = string1.split(", ");
String[] lastPart = stringArray[stringArray.length-1].split("*");
stringArray[stringArray.length-1] = lastPart[0];
Is there any easier way of making this code work? My objective is to get all the numbers separated, whether stringArray includes nonImportantData or not. Should I maybe use the substring method?
Actually, the String.split(...) method's argument is not a separator string but a regular expression.
You can use
String[] splitStr = string1.split(",|\\*");
where | is a regexp OR and \\ is used to escape * as it is a special operator in regexp. Your split("*") would actually throw a java.util.regex.PatternSyntaxException.
Assuming you always have the format you've provided....
String input = "123,234,345,456,567*nonImportantData";
String[] numbers = input.split("\\*")[0].split(",");
I'd probably remove the unimportant data before splitting the string.
int idx = string1.indexOf('*');
if (idx >= 0)
string1 = string1.substring(0, idx);
String[] arr = string1.split(", ");
If '*' is always present, you can shorten it like this:
String[] arr = str.substring(0, str.indexOf('*')).split(", ");
This is different than MarianP's approach because the "unimportant data" isn't preserved as an element of the array. This may or may not be helpful, depending on your application.

Categories

Resources