I am comparing file names in a folder ,I want to remove some part of string and check whether name exists or not
Here is my file name :
file1Name:AB-05012_MM-AB_585859_01
file2Name:AB-05012_MM-AB_732320_01-1
Now i want to compare the string only till
AB-05012_MM-AB_732320_01 ignore '-1'
Here is my logic
if (file1Name.equals(file2Name.contains(""))){
list.add(file1Name);
}
When you know there is an extra character in second file name then why not using
fileName2.startsWith ( fileName1)
or
int indexOfDot = fileName1.lastIndexOf(".");
fileName2.startsWith ( fileName1.subString( 0, indexOfDot)
But this is very specific to your problem. or for the cases where
fileName2 = fileName1 + any character or digit
You can try this:
String myStr = str.substring(0, str.lastIndexOf("-1"));
if your file name is same length:
if (file1Name.equals(file2Name.substring(0,24))){
//if same to some task
}
else:
if (file1Name.equals(file2Name.substring(0,file2Name.lastIndexOf('-')))){
//if same to some task
}
And I think the second solution better.
Related
I'm making a minecraft-forge mod and I'm having problems putting an String into Block#getBlockFromName(String name). the String:
String oreName = "minecraft:iron_ore -replace:minecraft:stone.minecraft:netherrack.minecraft:end_stone;";
And like you see after -replace: I have an block name (minecraft:stone) and a dot and than again block name and a dot. I want to split each block name into a separate String and read it one by one so I can insert it into Block#getBlockFromName and get 1 block out of each String. I tried using String#split(".") to split it into an array, but when I print out the array when I switched it back to String by using Arrays#toString it was empty. I want to split it by dots because I have an config file so those blocks can be changed to anything, I can't just pull out minecraft:stone out of the String because the ones who are using my mod will be able to configure that minecraft:stone to something else and add another block name by using a dot after the first block name.
This is what I've done so far:
String oreName = "minecraft:iron_ore -replace:minecraft:stone.minecraft:netherrack.minecraft:end_stone;";
String block1 = oreName.substring(oreName.indexOf("-replace:"));
String block2 = block1.replace("-replace:", "");
String block3 = block2.contains(" -") ? block2.substring(0, block2.indexOf(" ")) : block2.replace(";", "");
System.out.println("The Block Names Are: " + block3); // It prints it just without "minecraft:iron_ore -replace:" and ";" at the end
String[] block4 = block3.split(".");
System.out.println("The array: " + Arrays.toString(block4)); // only prints out "The array: []"
Problem is that String.split() takes regular expression as argument.
For your case you need to escape . symbol with:
String[] block4 = block3.split("\\.");
Which prints
The array: [minecraft:stone, minecraft:netherrack, minecraft:end_stone]
I am trying to read users id and their link type from a txt file. The data is given in following format.
SRC:aa
TGT:bb
VOT:1
SRC:cc
TGT:bb
VOT:-1
where 'SRC' and 'TGT' indicators of the users id. In data, some users ids are blank, i.e. users disagree to reveal their identities as following:
SRC:
TGT:cc
VOT:-1
SRC:ff
TGT:bb
VOT:1
In this case, I want to give them a special id, "anonymous". So, I wrote the following code:
//Reading source
dataline = s.nextLine();
String[] line1parts = new String[2];
.
.
//split the line at ":"
line1parts = dataline.split(":");
//if the line has source
if (line1parts[0].trim().equals("SRC")){
//if the soruce name is empty
if (line1parts[1].isEmpty()) {
src = "anonymous";
System.out.print("src: " + src);
}
//if the source already integer id
else {
src = line1parts[1].trim();
System.out.print("src: " + src);
}
}
The program shows java.lang.ArrayIndexOutOfBoundsException error. I have also tried if (line1parts[1].equals("") and if (line1parts[1].equals(null). Probably for the case SRC: (when empty) the string array is not creating any object (sorry if I am wrong. I am very new in java). How can I assign an user ID when it is empty? Thanks in advance.
If a line only contains SRC: the line1parts array will have only one item, thus line1parts[1] raises an ArrayIndexOutOfBoundsException .
Replace if (line1parts[1].isEmpty()) by if (line1parts.length < 2 )
Has StephaneM made me remember, the split method trim the empty cell during the splitting. This removed every empty cells at the end. This mean the empty cell if there is no SRC value in your case
To prevent this, you can call
java.lang.String.split(String, int)
This integer specify the length of the array you want, at minimum.
line1parts = dataline.split(":", 2);
You are sure to receive an array with length of 2 or more. So this could still remove some cells, but with a length constraint.
A good think to know is that if you send -1, the split will return EVERY cells. No trimming is done.
You are trying to get the index which is not present.
split() helps to divide value from regex you provided.
you are split the string
1."TGT:cc" in this case split method split String value from ":" and it is returning an array of size 2 i.e. [TGT,cc] (it has 0 and 1 index).
2.When you split the String "SRC:" in this case split method create an array of size 1 i.e [SRC] (it has only 0 index) because in this String after ":" nothing and so that it does not create extra index for null value.
When you call "line1parts[1].isEmpty()" it throw ArrayIndexOutOfBoundsException because it does not have the index 1.
Here you have to check "line1parts.length" before call "line1parts[1].isEmpty()".
line1parts = dataline.split(":");
// if the line has source
if (line1parts[0].trim().equals("SRC")) {
if (line1parts.length > 1) {
// if the soruce name is empty
if (line1parts[1].isEmpty()) {
src = "anonymous";
System.out.print("src: " + src);
}
// if the source already integer id
else {
src = line1parts[1].trim();
System.out.print("src: " + src);
}
}
}
Or-----------------
You have to do ::
line1parts = dataline.split(":",2);
I have a very simple question and just can't get my code to work in Java. I want to return a string that indicates a filepath, but extracts a certain portion of that path if it it exists.
So, my input might be "c:/lotus/notes/data/directory/mydatabase.nsf" and I want to return only "directory/mydatabase.nsf". Sometimes, the path provided will already leave out the "c:/lotus/notes/data/" because it is being accessed on the server rather than locally.
public String getDataPath ( String path ) {
int pathStart;
boolean pathContains;
String lowerPath;
lowerPath = path.toLowerCase();
pathStart = lowerPath.indexOf("c:/lotus/notes/data");
if ( pathStart >= 0) {
// 20 characters in "c:/lotus/notes/data/"
return path.substring(19);
}
pathContains = lowerPath.contains("lotus/notes/data");
if ( pathContains ) {
// 20 characters in "c:/lotus/notes/data/"
return path.substring(19);
}
return path;
}
This is simple, but somehow, I can't get it right. Neither of my if's ever evaluates as true.
Keep it simple:
path.replace("c:/lotus/notes/data", "");
You can simply do a path.replaceAll("c:/lotus/notes/data", ""). This will remove the leading path name if it is contained in the string, else the string will not change.
Take a look at the Path interface:
Paths Documentation
Path Documentation
It is used to do exactly what you want: Extract informations about the single parts of a path.
This question already has answers here:
How to get the filename without the extension in Java?
(22 answers)
Closed 9 years ago.
I am trying to get name of a File object without its extension, e.g. getting "vegetation" when the filename is "vegetation.txt." I have tried implementing this code:
openFile = fileChooser.getSelectedFile();
String[] tokens = openFile.getName().split(".");
String name = tokens[0];
Unfortunately, it returns a null object. There is a problem just in the defining the String object, I guess, because the method getName() works correctly; it gives me the name of the file with its extension.
Do you have any idea?
If you want to implement this yourself, try this:
String name = file.getName();
int pos = name.lastIndexOf(".");
if (pos > 0) {
name = name.substring(0, pos);
}
(This variation doesn't leave you with an empty string for an input filename like ".txt". If you want the string to be empty in that case, change > 0 to >= 0.)
You could replace the if statement with an assignment using a conditional expression, if you thought it made your code more readable; see #Steven's answer for example. (I don't think it does ... but it is a matter of opinion.)
It is arguably a better idea to use an implementation that someone else has written and tested. Apache FilenameUtils is a good choice; see #slachnick's Answer, and also the linked Q&A.
If you don't want to write this code yourself you could use Apache's FilenameUtils.
FilenameUtils.getBaseName(openFile.getName());
This will return the filename minus the path and extension.
I prefer to chop off before the last index of "." to be the filename.
This way a file name: hello.test.txt is just hello.test
i.e.
int pos = filename.lastIndexOf(".");
String justName = pos > 0 ? filename.substring(0, pos) : filename;
You need to handle there being no extension too.
String#split takes a regex. "." matches any character, so you're getting an array of empty strings - one for each spot in between each pair of characters.
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String)
There are two problems with your code...
1) Just using "." as an argument to split is being interpreted as a Rejex that you don't want. You want a literal dot. So you have to escape it...
openFile.getName().split("\\.");
2) You will incorrectly parse any file with more than one dot. The best way to do this is to search for the last dot and get the substring...
int pos = openFile.getName().lastIndexOf(".");
if(pos != -1) {
String name = openFile.getName().substring(0, pos);
}
You can try split("\\.");. That is, basically escaping the . as it's treated as all characters in regex.
So I want to search through a string to see if it contains the substring that I'm looking for. This is the algorithm I wrote up:
//Declares the String to be searched
String temp = "Hello World?";
//A String array is created to store the individual
//substrings in temp
String[] array = temp.split(" ");
//Iterates through String array and determines if the
//substring is present
for(String a : array)
{
if(a.equalsIgnoreCase("hello"))
{
System.out.println("Found");
break;
}
System.out.println("Not Found");
}
This algorithm works for "hello" but I don't know how to get it to work for "world" since it has a question mark attached to it.
Thanks for any help!
Take a look:
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#contains(java.lang.CharSequence)
String.contains();
To get a containsIgnoreCase(), you'll have to make your searchword and your String toLowerCase().
Take a look at this answer:
How to check if a String contains another String in a case insensitive manner in Java?
return s1.toLowerCase().contains(s2.toLowerCase());
This will also be true for:
war of the worlds, because it will find world. If you don't want this behavior, youll have to change your method like #Bart Kiers said.
Split on the following instead:
"[\\s?.!,]"
which matches any space char, question mark, dot, exclamation or a comma (add more chars if you like).
Or do a temp = temp.toLowerCase() and then temp.contains("world").
You dont have to do this, it's already implemented:
IndexOf and others
You may want to use :
String string = "Hello World?";
boolean b = string.indexOf("Hello") > 0; // true
To ignore case, regular expressions must be used .
b = string.matches("(?i).*Hello.*");
One more variation to ignore case would be :
// To ignore case
b=string.toLowerCase().indexOf("Hello".toLowerCase()) > 0 // true