Android find array index value of a partial match - java

I'm looking for a way to find the index position of a partial match in Java (Android).
Let's say my Array is:
String ips[] = {"10.185.98.111", "192.168.0.13", "Some random IPV6 address"};
I'd like to be able to something like ips[].indexOf("192") and this return "1" rather than "-1".
Is this possible?

Do your own function such as:
public int getElementThatContains(String[] ips, String key) {
for (int i = 0; i < ips.length; i++) {
if (ips[i].indexOf(key) >= 0) {
return i;
}
}
return -1;
}
Observe that the ordering of your list will determine which ip you'll get.
If you have two elements with 192 whichever is closer to the beginning will get selected.
Also you may change:
if (ips[i].indexOf(key) >= 0) {
return i;
}
To different kind of matches such as:
ips[i].contains(key)
ips[i].startsWith(key)
ips[i].endsWith(key)

public void specialIndexOF(List<String> ips){
int index=0;
for(String s:ips){
if(s.contains(search)){
return index;
}
index++;
}
return -1;
}

Related

Rewriting the whole String Class methods

My professor have given me a challenging homework, where the idea is to rewrite all the methods in the String classes without using String, StringBuilder, and Wrapper classes. This is for Intro to Java class. I already have some methods done but having a hard time with some other ones. This is for the main class only with no creation of any string inside.
What I have: a "data" as a char[] data for my "MyOwnString" object.
CompareTo method:
public int compareTo(MyOwnString rhs){
if (this.data == rhs.data){
return 0;
} else if (this.data > rhs.data){
return 1;
}
else {
return -1;
}
}
This one shows an error. My guess is that the rhs needs to be declare before being able to compare to any string being assigned to a MyOwnString object.
Since there is a compareTo method and a compareToIgnoreCase, then I would have to add a line to ignore the comparsion?
Update:
This is the code I went with for the compareTo method by creating own method using length of the array.
public int compareTo(MyOwnString cts){
int word1 = data.length;
int word2 = cts.length();
int result = 0;
for (int i=0; i<word1; i++){
for (int j=0;j<word2; j++){
if(word1 == word2){
result = 0;
}
else if (word1 > word2){
result = 1;
}
else {
result = -1;
}
}
}
return result;
}
Since you are not allowed to use String.compareTo()
and since java doesn't support > for your custom objects or char[] for that matter (e.g doesn't support operator overloading) you have to do it programmatically.
In other words you have the two char arrays and you have to loop through all the characters. You compare the first two characters from each of the char arrays (there you can use > or <) if they are == you compare the second two characters and so on.. till you find two characters that break the tie - you can then break your for loop and return the result as -1, 1. If they are tied on every character you return 0.
If you want to implement equals you could just call compareTo and optimize it a bit by checking the lengths of the strings. If they are different then of course the strings are not equal
Update: I am not sure if you ran your code above - try to compile your code and run it before you move forward. I believe it won't even compile.
Here is, I believe, a correct unchecked version. I could have mixed the -1 and 1s as always..
public int compareTo(MyOwnString cts){
int word1Length = ((MyOwnString)this).data.length;
int word2Length = cts.data.length;
for (int i=0; i < Math.min(word1Length,word2Length); i++){
if(this.data[i] == cts.data[i]){
continue;
}
else if (this.data[i] > cts.cts[i]){
return -1;
}
else if (this.data[i] < cts.cts[i]) {
return 1;
}
}
if (word1Length == word2Length){
return 0;
}
else if(word1Length < word2Length){
return 1;
}
else {
return -1;
}
}
public boolean equals(MyOwnString cts){
int word1Length = ((MyOwnString)this).data.length;
int word2Length = cts.data.length;
if (word1Length != word2Length){
return false;
}
else { // if they are equal
int comparison = this.compareTo(cts);
if (comparison==0){
return true;
}
else {
return false;
}
}
}
You can't compare char[] objects with the > operator, since it's not defined on them. You'll have to iterate over the char[] arrays and compare the characters yourself.
BTW, it's very easy to cheat in this assignment, since the code of the String class is available online.

Search String array for String

I want a command such as this:
setstat <statname> <level>
However, my 'statname's are in a Array; and I need to output the Array number.
This is the code I am using:
String[] statname = {"att", "def", "str", "hp",
"ranged", "pray", "magic", "cooking",
"wc", "fletch", "fish", "fm",
"craft", "smith", "mining", "herb",
"agil", "thieving", "slayer", "farming", "rc"};
int statid = statname.contains(arg[1]);
However, it doesn't work (for me). Seeing as contains(...) isn't compatible with an String[] array.
I have no idea which method to use, or how to handle this.
Use Arrays.asList(statname).indexOf(arg[1]); to find the index of an item.
Since your array is not ordered, this function will work:
public int getFoundIndex(String[] stringArr_toSearch, String str_toFind)
for(int i = 0; i < stringArr_toSearch.length; i++) {
if(stringArr_toSearch[i].equals(str_toFind)) {
return i;
}
}
return -1;
}
Call it with
int foundIdx = getFoundIndex(statName, "str");
Here's a neat code for the linear search which returns the index of the element in the array if the element is found, else returns false.
public int search(String[] array, String element)
{
if(array == null || element == null)
return -1;
for(int i = 0; i < array.length; i++)
{
if(array[i].equals(element))
return i;
}
return -1;
}
Using the approach: Arrays.asList(statname).indexOf(arg[1); can get expensive, if you have to search for the elements a lot of time.
You can sort your array once, and then do a binary search too, in order to achieve faster lookup times, if you have to search for elements in the statname array multiple times.

Searching for a string within an array

Below I am trying to create a method which searches through an array for a certain string and returns the position of it, if not there then -1 should be the number returned. Below I search for a word using the method and it returns -1 even though the word is within the array. Why is this?
String answer = "";
System.out.println("Enter word to search within array");
answer = in.next();
public static int search(String[] theWords, String answer) {
int a = -1;
for(int i = 0; i < theWords.length; i++) {
if (answer.equals(theWords[i])){
a = i;
break;
}
}
return a;
}
I can't see anything wrong with the code, but I would recommend eliminating the local variable that holds the return value:
public static int Search(String[] thewords, String answer) {
for (int i = 0; i < thewords.length; i++) {
if (answer.equals(thewords[i])){
return i;
}
}
return -1;
}
With this simplified logic, there's little or no chance of there being a bug in this code.
I assume this is course work, and you are not allowed to use library methods. If you were allowed, your method could be a single line:
return Arrays.asList(theWords).indexOf(answer);
You can optionally make a copy of the array since sorting might be unwanted for consumers of the method
public static int Search(String[] thewords, String answer) {
if(thewords == null) {
throw new NullPointerException();
}
String[] copy = new String[thewords.length];
System.arraycopy(thewords,0,copy,0,copy.length);
Arrays.sort(thewords);
return Arrays.binarySearch(thewords, answer);
}
Note: It returns -pos and not -1
If you need -1:
public static int Search(String[] thewords, String answer) {
if(thewords == null) {
throw new NullPointerException();
}
String[] copy = new String[thewords.length];
System.arraycopy(thewords,0,copy,0,copy.length);
Arrays.sort(thewords);
int idx = Arrays.binarySearch(thewords, answer);
return idx < 0? -1:idx;
}
Concerning your code: I believe the problem would be related to casing or spacing:
Replace with something like: if (answer.equalsIgnoreCase(theWords[i].trim())){
For large arrays go with binary search.

java creating a class method that searches an array for word length

so i've already made a class method that searches for a specific word, but (like most times i find myself on here!) i've had a brain malfunction and can't figure out how to modify it to do what i need. here's what i've got so far:
private static int findFourLetterWord(String[] strings, String key) {
for (int i = 0; i < strings.length; i++)
if (strings[i].equals(key))
return i;
return -1;
}
so this searches an array for 'key' and returns with it's position if it is found. what i'm trying to get it to do is search an array of strings for the first 4 letter word it encounters and return with that word. i would change the first return to be System.out.println(strings[i]); i believe, but i'm not sure how to make it search for the first 4 letter word it finds. tried using a bunch of convoluted substrings but that didn't work. any advice or guidance would be great. thank you in advance.
Your current method is close; you just need to change the condition in the for-loop to check for a length of 4 using String#length() rather than equality to a key argument.
private static String findFourLetterWord(String[] strings) {
for (String str : strings) {
if (str.length() == 4) {
return str;
}
}
return null;
}
Never forget to consult the JavaDocs when you find yourself unsure of what methods are available for your convenience.
Am I understanding your question right?
private static String findFourLetterWord(String[] strings) {
for (int i = 0; i < strings.length; i++)
if (strings[i].length()==4)
return strings[i];
return null;
}
Use substring function to get the first 4 character of the key and string as below:
private static int FindFourLetterWord(String[] strings, String key) {
//Assuming key length is 4 or more
String keyWithFourChars = key.substring(0,4);
for (int i = 0; i < strings.length; i++){
if(strings[i].length() > 3){
if (strings[i].substring(0,4).eqauls(keyWithFourChars)){
return i;
}
}
}
return -1;
}
If you want to just look for 4 chars string, then simply check the length as below:
In this case, you don't need to pass key as parameter.
private static int FindFourLetterWord(String[] strings) {
for (int i = 0; i < strings.length; i++){
if(strings[i].length() == 4){
return i;
}
}
return -1;
}

For with if statement java

I need to chek where the char c index is on string , and if the char c is'nt there - return -1.
public class Find {
private String _st;
int i;
public Find(String st) {
_st = st;
}
public int whatIstheIndex(char c) {
for (i=0;i<_st.length();i++)
if (_st.charAt(i) == c) {
return i;
} else {
return -1;
}
return i;
}
}
I'm getting always -1. Why? Is the last return i; unnecessary?
Remove the else clause, it's returning -1 if the first character in the string isn't correct.
You would then also need to change the return statement at the end of the method.
Why don't you just use the built-in indexOf method? That would be a lot easier and quicker than looping through the string and testing each and every character.
But if you have to use this method for some strange reason, get rid of your else clause, because it makes the function return -1 every time the character tested is not matched.
Here is an alternative solution which also works.
public int whatIstheIndex(char c) {
int result = -1;
for (int i = 0; i < _st.length(); i++) {
if (_st.charAt(i) == c) {
result = i;
}
}
return result;
}
It's just a different way of thinking about the problem. I suppose it's slightly "worse" because it adds an extra line of code, but I hope you see how/why this works.
Your code should be like this:
public int whatIstheIndex(char c) {
for (int i = 0; i < _st.length(); i++)
if (_st.charAt(i) == c) {
return i;
}
return -1;
}
Hope this helps!
Why not use String.indexOf(int) method.
public int whatIstheIndex (char c) {
return _st.indexOf(c);
}
Else, return a -1 only after the loop finishes:
public int whatIstheIndex (char c) {
for (i=0;i<_st.length();i++)
if (_st.charAt(i) == c ) {
return i;
}
}
return -1;
}
What's happening is that it's looking at the first character, and if that doesn't match, it immediately returns -1 (and hence, doesn't continue looping through the chars until it finds the right one).
You need to return -1 only if you have finished the for loop and have not found the character. So it needs to be:
public int whatIstheIndex(char c) {
for (i = 0; i < _st.length(); i++) {
if (_st.charAt(i) == c) {
return i;
}
}
return -1;
}
You are always returning after looking at the first character. Your test doesn't look at other characters. A debugger would show you this. The last return i is only called if the length is 0.
Your current implementation will only ever return one of two values, 0, or -1. 0 is returned when the first index is that which the character resides, or -1 if its not found there. Remove the else clause and return -1 after you've finished the for loop to indicate that you've exhaustively searched all indexes, and found no answer.

Categories