Searching for a String in a String array [duplicate] - java

This question already has answers here:
Checking if String x equals any of the Strings from String[]
(12 answers)
Closed 9 years ago.
while writing my program I have run into another nooby road block.
if(StringTerm[0].equals("wikipedia"))
{
StringBuilder SearchTermBuilder = new StringBuilder();
for(int i = 1; i < StringTerm.length; i++)
{
SearchTermBuilder.append(StringTerm[i] + " ");
}
// This is the string it outputs.
WIKI_ID = "Wikipedia";
SearchTerm = SearchTermBuilder.toString();
SearchTermFull = WikiBaseLinkReference.WIKI_WIK + SearchTermBuilder.toString();
}
This code checks for input from a console command "/wiki" and checks to see if the first string after the word "wiki" matches "wikipedia" and if so, it builds a string to match what I want it to do.
This is all well and good, and the program works fine, but I want users to be able to use different keywords to get the same results.
For Example: If I type /wiki wikipedia, it would do the same as /wiki pediawiki
If I made an array of different names called WIKIPEDIA
public static String WIKIPEDIA[] = {"wikipedia","pediawiki"};
How would I tell the if statement to check to see if the text entered equals one of the strings inside of my array? Every time I try to use an || or operator it throws me some errors.
Thanks in advance.

You need a version of "any":
public boolean any(String[] array, String s) {
for(String value : array) {
if(s.equals(value)) { return true; }
}
return false;
}
Then
if(any(WIKIPEDIA, "wikipedia")) {
}

Related

Looking for similar strings in a string array [duplicate]

This question already has answers here:
How to search an array for a part of string?
(6 answers)
Closed 1 year ago.
I have a string array. For example:
["Tartrazine","Orange GGN", "Riboflavin-5-Phosphate"]
And I have a string. For example:
"Riboflvin"
I want to look for most similar string in the array and get it if it exists.
So I need this output:
"Riboflavin-5-Phosphate"
But if the array looks like this:
["Tartrazine","Orange GGN", "Quinoline"]
I want something like this output:
"No similar strings found"
I tried using FuzzyWuzzy library, but it shows a lot of false alarms.
You can use String#contains method, sequentially reducing the length of the string to search if the full string is not found:
String[] arr = {"Tartrazine", "Orange GGN", "Riboflavin-5-Phosphate"};
String element = "Riboflvin";
boolean found = false;
for (int i = 0; i < element.length(); i++) {
// take shorter substring if nothing found at previous step
String part = element.substring(0, element.length() - i);
// if any string from array contains this substring
if (Arrays.stream(arr).anyMatch(str -> str.contains(part))) {
System.out.println("Found part: " + part);
// then print these strings one by one
Arrays.stream(arr).filter(str -> str.contains(part))
.forEach(System.out::println);
found = true;
break;
}
}
// if nothing found
if (!found) {
System.out.println("No similar strings found");
}
Output:
Found part: Ribofl
Riboflavin-5-Phosphate
Well, it depends what you want to do exactly.
There are a couple of things you can do you can check wether the array contains an exact match of the String you are looking for by just calling list.contains("yourStr") the list directly. You could also check each value to see whether it contains a certain substring like so:
foreach(String s : list) {
if (s.contains(subStr) {
return s;
}
}
Otherwise, if you really would like to check similarity it becomes a bit more complicated. Then we really have to answer the question: "how similar is similar enough?". I guess this post as a decent answer to that problem: Similarity String Comparison in Java

Replace a Name with String of asterisk at charAt() to a given char but don't replace all of asterisk but only at the position where it matches [duplicate]

This question already has answers here:
Replace a character at a specific index in a string?
(9 answers)
Closed 4 years ago.
public class Main {
public static void main(String[] args) throws Exception {
String name = "eric";
String nameForYou = name.replaceAll(".","*");
String afterGuess="";
System.out.println("Guess my name: "+nameForYou+" "+name.length());
String yourguess = "c";
for (int i=0;i<name.length();i++) {
if ((yourguess.charAt(0) == name.charAt(i))){
afterGuess = nameForYou.replace(nameForYou.charAt(i),yourguess.charAt(0));
}
}
System.out.println(afterGuess);
}
}
I want output as:
Guess my name: **** 4
***c
I don't want it to replace all the "*"
Your strategy does not work, because replace replaces the first character that it finds, which is not necessarily the character in the right position.
Since Java String is immutable, a better approach for your replacement code should be to make a char array of the appropriate length, and convert it to String only for printing:
String name = "eric";
char[] nameForYou = name.replaceAll(".","*").toCharArray();
System.out.println("Guess my name: "+new String(nameForYou)+" "+name.length());
String yourguess = "c";
for (int i=0;i<name.length();i++) {
if ((yourguess.charAt(0) == name.charAt(i))){
nameForYou[i] = yourguess.charAt(0);
}
}
System.out.println(new String(nameForYou));
Java arrays are mutable, so you have direct control over characters at a specific index. You could also use StringBuilder if you prefer not to deal with arrays directly.

Trying to reverse a string on Java. Why can't I get the reversed text as my only output? [duplicate]

This question already has answers here:
Reverse a string in Java
(36 answers)
Closed 5 years ago.
I can't get my function to return the reversed string. I keep getting the original string, plus the reversed sting attached together.
P.S this is obviously a question from someone new. Cut me some slack and save me from the horribly demoralizing down vote.
int i;
reverse = reverse.replaceAll("[^a-zA-Z]+", "").toLowerCase();
for (i = reverse.length() - 1; i >= 0; i--) {
reverse = reverse + reverse.charAt(i);
}
return reverse;
}
You need another String (or some other method / memory) to build your return value (consider "a", starting from the end of the String add "a" - thus you get "aa"). Instead, I would use a StringBuilder - and the entire method might be written like
return new StringBuilder(reverse.replaceAll("[^a-zA-Z]+", "")
.toLowerCase()).reverse().toString();
Change the snippet to,
String reverse_string="";
for (i = reverse.length() - 1; i >= 0; i--) {
reverse_string += reverse.charAt(i);
}
return reverse_string;
You will need a separate String variable to contsruct the newly reversed string.
Why not just let the existing Java api do this for you?
String someString = "somestring123";
System.out.println(new StringBuilder(someString).reverse().toString());
output:
StringBuilder

JAVA: method, how many occurrences of a string appear in another string [duplicate]

This question already has answers here:
Find the Number of Occurrences of a Substring in a String
(27 answers)
Closed 6 years ago.
I'm new into learning about java programming and here I got stuck to this assignment. I can't figure out what I did wrong in the code so I can get the specific result. Any help or tips in how to solve the problem will be helpful. Thanks in advanced.
This assignment will write a method to determine how many occurrences of a string appear in another string.
Specifically, you should do the following:
Create a new Java Class named Part2in the StringsSecondAssignments project.
Write the method named howMany that has two String parameters named stringa and stringb. This method returns an integer indicating how many times stringa appears in stringb, where each occurrence of stringa must not overlap with another occurrence of it. For example, the call howMany(“GAA”, “ATGAACGAATTGAATC”) returns 3 as GAA occurs 3 times. The call howMany(“AA”, “ATAAAA”) returns 2. Note that the AA’s found cannot overlap.
Write the void method testHowMany has no parameters. Add code in here to call howMany with several examples and print the results. Think carefully about what types of examples would be good to test to make sure your method works correctly.
Here is my code:
public class Part2in {
public String HowMany(String stringa, String stringb) {
int lastIndex = 0;
int count = 0;
while (lastIndex != -1){
lastIndex =stringb.indexOf(stringa, lastIndex);
if(lastIndex !=-1){
count = count + 1;
lastIndex = stringa.length();
}
System.out.println(count);
}
return "";
}
public void testHowMany() {
String stringB = "ABCDASDFBCSDSDFBCBDSDBC";
String stringA = "BC";
String counts = HowMany(stringB, stringA);
if (counts.isEmpty()) {
System.out.print("ERROR" );
}
else {
System.out.print("CORECT" + counts);
}
}
}
a simple while could do the work:
#Test
public void testIt(){
String a = "abcdesdikdikcdkofkvcdqwppqcddddcdlpqa";
String b = "cd";
int i = 0;
while (a.contains(b)){
a = a.replaceFirst(b,"");
i++;
}
System.out.println("found:"+i);
}
which prints you in my case 5
You can do this in one line:
System.out.println("ATAAAA".split("AA", -1).length - 1);

Program not noticing when the string is equal to a specific string [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I've been trying to create a program that censors a word but I was having difficulty with that so I tried going back to some of the fundamental code and testing it and I am coming across an odd result.
import java.util.Scanner;
public class TextCensor
{
public static void main(String[] args)
{
String input;
Scanner keyboard = new Scanner(System.in);
input = keyboard.nextLine();
int length = input.length() - 1;
if (length + 1 >= 3)
{
for (int i=0; i<(length - 1); i=i+1 )
{
char first = input.charAt(i);
char second = input.charAt(i+1);
char third = input.charAt(i+2);
String censorCheck = "" + first + second + third;
if (censorCheck == "tag")
{
System.out.println("success");
}
else
{
System.out.println(censorCheck);
}
}
}
else
{
System.out.println(input);
}
}
}
If I input the string "adtag" I will obtain the following output:
adt
dta
tag
yet "success" will never be printed despite the fact that I have printed a censorCheck that is equal to "tag".
String is an object. You have to compare objects by equals():
censorCheck.equalsIgnoreCase("tag")
Ignore case works fir upper letters as well.
Only for primitives you can use comparison by ==:
3 == 3
You are trying to check whether both instance of String is same or not instead of checking contents of both string.
You should try censorCheck.equals("tag") .
To compare whether contents of two string are equal or not in JAVA you should use the equals() method. You cannot compare the value of two string by the == operator . In your case use if (censorCheck.equals("tag")) and see if you get the desired result.

Categories

Resources