equality between two strings - java

I have a text file with this structure:
CRIM:Continuius
ZN:Continuius
INDUS:Continuius
CHAS:Categorical
NOX:Continuius
I inserted it into a two dimensional array:
BufferedReader description = new BufferedReader(new FileReader(fullpath2));
String[][] desc;
desc = new String[5][2];
String[] temp_desc;
String delims_desc = ":";
String[] tempString;
for (int k1 = 0; k1 < 5; k1++) {
String line1 = description.readLine();
temp_desc = line1.split(delims_desc);
desc[k1][0] = temp_desc[0];
desc[k1][1] = temp_desc[1];
}
and then tried to identify which attribute is Categorical:
String categ = "Categorical";
for (int i=0; i<5; i++){
String temp1 = String.valueOf(desc[i][1]);
if ("Categorical".equals(desc[i][1])){
System.out.println("The "+k1+ " th is categorical.");
}
}
Why doesn't it return true, although one of the attributes is categorical?

Looking at the input you posted (in the edit perspective), I saw there is a lot of trailing whitespace on almost every line of the textfile. Your problem will disappear if you replace
desc[k1][1] = temp_desc[1];
with
desc[k1][1] = temp_desc[1].trim();
You could even shorten your code to
for (int k1 = 0; k1 < 5; k1++) {
String line1 = description.readLine().trim();
desc[k1] = line1.split(delims_desc);
}
Clarification:
You are trying to compare
"Categorical" // 11 characters
with
"Categorical " // more than 11 characters
and those are not equal strings.

Related

Optimized code two get uncommon charaters in two strings( following the flames game rule)

My Interviewer asked me to write optimized code for FLAMES Game
The rules of games are following.
1-Take two names (i.e. - 'naveen' and 'tejveer')
2-Compare these two string to get uncommon characters like
naveen
tejveer
bold characters are common in both and should be removed
NOTE- If there is one character occurs two times in string1 and same character occurs 3 times in another string then there is two characters treated as common and one as uncommon
3-Remove the common characters (three common characters in this example 'e', 'v' , 'e')
4-Get the count of the characters that are left (after removing common characters 7 characters left and these are - n , a , n , t , e , j , r.)
I have write these two functions.
//This is normal function (without two much optimization)
private static void flames2(String name1 , String name2){
int n1Length = name1.length();
int n2Length = name2.length();
StringBuilder target;
StringBuilder player;
int oCounter;
int iCounter;
if(n1Length > n2Length){
player = new StringBuilder(name1);
target = new StringBuilder(name2);
oCounter = n1Length;
iCounter = n2Length;
}else{
player = new StringBuilder(name2);
target = new StringBuilder(name1);
oCounter = n2Length;
iCounter = n1Length;
}
int matches = 0;
for(int i = 0; i< oCounter ; i++){
for(int j = 0;j < iCounter ; j++){
if(player.charAt(i) == target.charAt(j)){
char chTemp = target.charAt(j);
target.setCharAt(j , target.charAt(iCounter-1));
target.setCharAt(iCounter-1 , chTemp);
iCounter--;
matches++;
break;
}
}
}
int unmatchedChars = name1.length()+name2.length()-2*matches;
System.out.println("result "+unmatchedChars);
}
and then He told me to do this problem by using one for loop and I tried this function which is somewhat optimized.
private static void flames3(String name1 , String name2){
int n1Length = name1.length();
int n2Length = name2.length();
StringBuffer target;
String player;
int oCounter;
if(n1Length < n2Length){
target = new StringBuffer(name2);
player = name1;
oCounter = n1Length;
}else{
target = new StringBuffer(name1);
player = name2;
oCounter = n2Length;
}
int matches = 0;
for(int i = 0; i< oCounter ; i++){
int index = target.toString().indexOf(player.charAt(i));
if(index >= 0){
target.setCharAt(index,'_');
matches++;
}
}
int unmatchedChars = name1.length()+name2.length()-2*matches;
System.out.println("result "+unmatchedChars);
}
But In function flames3 I am using String.IndexOf() which use a for loop to check the character.
In these functions I am just counting the matched characters.
So there is a way to write more optimized function.
Following thing may work fine in optimised way.
public void flames(String name1, String name2) {
List<String> list1 = new ArrayList<>();
List<String> list2 = new ArrayList<>();
for (int i = 0; i < name1.length(); i++) {
list1.add(String.valueOf(name1.charAt(i)));
}
for (int i = 0; i < name2.length(); i++) {
list2.add(String.valueOf(name2.charAt(i)));
}
List<String> union = new ArrayList<String>(list1);
union.addAll(list2);
List<String> intersection = new ArrayList<String>(list1);
intersection.retainAll(list2);
union.removeAll(intersection);
for (String n : union) {
Log.d("item", n);
}
}

Splitting tokens into tokens using delimiters in Java

I have the following txt file that I need to split with tokens and save to an object:
1,Harry Potter,4,3,11,14,20
2,Matrix,3,1,8,12
3,Batman,3,39,9,42
Structure is: id, name, length, movieIds
Where length is reference to how many movieIds there are.
Not sure how to split movieIds separately or to set multiple values to the object as they override one another.
Scanner inputFile = new Scanner(playlistLibrary);
String str;
String[] tokens;
for (int i = 1; i < playlist.length; i ++) {
playlist[i] = new Playlist_17967352();
if (inputFile.hasNext()) {
str = inputFile.nextLine();
tokens = str.split(",");
for (int a = 0; a < tokens.length; a ++) {
playlist[i].setId(tokens[0]);
playlist[i].setName(tokens[1]);
playlist[i].setLength(tokens[2]);
if (tokens.length > 3) {
int length = Integer.parseInt(playlist[i].getLength());
String movieIds;
for (int b = 0, c = 3 ; b < length; b++, c++) {
movieIds = tokens[c];
playlist[i].setMovies(movieIds);
}
}
} // end for tokens.length
System.out.println(playlist[i].getMovies());
Code output:
20
12
42
What I need is:
3,11,14,20
1,8,12
39,9,42
You can just do one split. You know that the first movie id is at tokens[3], so you only need one counter in your loop and then add 3 when indexing tokens.

How do I split a string into even parts then populate an array with those new strings?

I am working on a program and I will be asking the user to input a string full of characters with no spaces. I will then be splitting this string up into parts of three characters each, and I would like to populate an array with these new strings of three characters. So basically what I am asking is how would I create a method that takes an input string, splits it up into separate parts of three, then populates an array with it.
while (i <= DNAstrand.length()-3) {
DNAstrand.substring(i,i+=3));
}
This code will split the string up into parts of three, but how do I assign those values to an array in a method?
Any help is appreciated thanks!
Loop through and add all the inputs to an array.
String in = "Some input";
//in.length()/3 is automatically floored
String[] out = new String[in.length()/3];
int i=0;
while (i<in.length()-3) {
out[i/3] = in.substring(i, i+=3);
}
This will ignore the end of the String if it's length isn't a multiple of 3. The end can be found with:
String remainder = in.substring(i, in.length());
Finally, if you want the remainder to be part of the array:
String in = "Some input";
//This is the same as ceiling in.length()/3
String[] out = new String[(in.length()-1)/3 + 1];
int i=0;
while (i<in.length()-3) {
out[i/3] = in.substring(i, i+=3);
}
out[out.length-1] = in.substring(i, in.length());
Try this:
private static ArrayList<String> splitText(String text)
{
ArrayList<String> arr = new ArrayList<String>();
String temp = "";
int count = 0;
for(int i = 0; i < text.length(); i++)
{
if(count < 3)
{
temp += String.valueOf(text.charAt(i));
count++;
if(count == 3)
{
arr.add(temp);
temp = "";
count = 0;
}
}
}
if(temp.length() < 3)arr.add(temp);//in case the string is not evenly divided by 3
return arr;
}
You can call this method like this:
ArrayList<Strings> arrList = splitText(and the string you want to split);

Convert comma separated string to array without string split?

Using Java, how would I convert "Paul, John, Ringo" to
Paul
John
Ringo
But while using a loop that searches for the commas and pulls out the words between them? I can't use anything like string split, strictly a loop and pretty simple java. Thanks!
String str = "Paul, John, Ringo";
List<String> words = new ArrayList<String>();
int cIndex = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ',') {
String temp = str.substring(cIndex, i).trim();
cIndex = i + 1;
words.add(temp);
}
}
String temp = str.substring(str.lastIndexOf(',')+1,str.length()).trim();
words.add(temp);
List<String> list = new List<String>();
String text = "your, text, here";
int indexTraversed = 0;
while(true){
int i = text.indexOf(",", indexTraversed);
if(i<0) break;
list.add(text.substring(indexTraversed, i));
indexTraversed += i + 1;
}
String[] array = list.toArray();
and if you can't use List :
String[] list = new String[100];
int counter = 0;
String text = "your, text, here";
int indexTraversed = 0; // declaring and assigning var
while(true){
int i = text.indexOf(",", indexTraversed);
if(i<0) break;
list.add(text.substring(indexTraversed, i));
indexTraversed += i + 1;
counter ++;
}
Then read the list array until counter.

How to get the right substring after split?

I have a string like this:[name ;24, name;23, name;22]. How can i split this string to obtain only the numbers after";"?
String s = "[name ;24, name;23, name;22]";
String couples[] = s.replace("]", "").split(",");
int ages[] = new int[couples.length];
for (int i=0; i< couples.length; i++)
ages[i] = Integer.parseInt(couples[i].split(";")[1]);
// Your input looks like this.
String s = "[name ;24, name;23, name;22]";
String[] numberStrings = s
// First get rid of the known prefix and suffix
.substring("[name ;".length(), s.length - "]".length())
// Then split on the repeated portion that occurs between numbers.
.split(", name;");
yet another method
String str = "name ;24, name;23, name;22";
int p = 0;
while ((p = str.indexOf(";", p + 1)) > -1) {
System.out.println(str.substring(p+1).split("[^0-9]")[0]);
}

Categories

Resources