This question already has answers here:
How to check if a String contains another String in a case insensitive manner in Java?
(19 answers)
Closed 8 years ago.
I wrote a code to find a substring within a string in java but i want to know is there a short way to do this or is there a inbuilt function to do this.
Here's the code :
import java.util.*;
class substr
{
public static void main (String args [])
{
String str1 = new String();
String str2 = new String();
String str3 = new String();
int check=1,k;
Scanner obj= new Scanner (System.in);
System.out.println("Enter a string");
str1=obj.nextLine();
System.out.println("Enter Sub String");
str2=obj.nextLine();
int len=str1.length();
System.out.println(check);
for( int c = 0 ; c < len&&check!=0 ; c++ )
{
for( int i = 1 ; i <= len - c&& check!=0 ; i++ )
{
str3 = str1.substring(c, c+i);
if (str2.equals(str3))
{
check=0;
}
}
}
System.out.println(check);
if (check==0)
{
System.out.println("Sub String");
}
else if ( check==1)
{
System.out.println("No");
}
}
}
If you are asking for a way to do what your code does (check if a string is substring of another string), you can use String#contains:
if(str1.contains(str2)) {
System.out.println("Sub String");
} else {
System.out.println("No");
}
You can also use String#indexOf:
if(str1.indexOf(str2)>=0) {
System.out.println("Sub String");
} else {
System.out.println("No");
}
Related
As of now I am making a small program that compares two string with the outcome of true and false. However, the program needs to say true if it visually looks the same. for example if it say box and b0x then it would be true. As of now the outcome is looking false as shown below.
Enter First String:
box
Enter Second String:
b0x
false
the string below needs to be considered the same
0, o and Q
1, I and T
2 and Z
5 and S
8 and B
below is my current work
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter First String:");
String str1 = sc.nextLine();
System.out.println("Enter Second String:");
String str2 = sc.nextLine();
sc.close();
String string1 = new String("0");
String string2 = new String("o");
String string3 = new String("q");
String string4 = new String("1");
String string5 = new String("l");
String string6 = new String("T");
String string7 = new String("2");
String string8 = new String("z");
String string9 = new String("5");
String string10 = new String("s");
String string11 = new String("8");
String string12 = new String("b");
// Comparing for String 3 = String 4
if (str1.equals(str2))
{
System.out.print(true);
}
else if(string1.equals(str1))
{
System.out.print(true);
}
else if(string2.equals(str2))
{
System.out.print(true);
}
else
{
System.out.print(false);
}
}
}
}
Is there any algorithm that I can use or any way where the program can detect as true even when they are visually the same. I appreciate any help, thank you
The answer to this question (as well as most questions about pattern matching in Strings) is regular expressions. All you need to do is use replaceAll for all your character transformations to normalize your strings.
like:
str1 = str1.replaceAll("[oQ]", 0);
str1 = str1.replaceAll("[IT]", 1);
First of all, when you declare String variables, you don't have to make a constructor call each time.
String string1 = "0" // that is fine. No need to call constructor.
Then, I advise you to create a collection of all the characters that are supposed to look the same.
Iterate over all the characters of the first input, and check if :
each character of the first input is equal to each character of the second input
if it is a "look visually the same character", check if second input contains the associated(s) character(s).
According to the data you provided, I suggest you this solution, though it is not the perfect one :
import javafx.util.Pair;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
private static List<List<Character>> charactersVisuallyLookingTheSame = new ArrayList<>();
public static void main(String[] args) {
initCharactersThatLookTheSame();
Scanner sc = new Scanner(System.in);
System.out.println("Enter First String:");
String str1 = sc.nextLine();
System.out.println("Enter Second String:");
String str2 = sc.nextLine();
sc.close();
boolean equal = equalsVisually(str1, str2);
System.out.println(equal);
}
private static boolean equalsVisually(String first, String second)
{
// some checks just in case...
if(first == null || second == null)
{
return false;
}
// to be equal visually, they must have the same length.
if(first.length() != second.length())
{
return false;
}
char[] firstAsArray = first.toCharArray();
char[] secondAsArray = second.toCharArray();
for(int i = 0; i < firstAsArray.length; i++)
{
// if it is different
if(firstAsArray[i] != secondAsArray[i])
{
if(!isCharVisuallyLookingTheSame(firstAsArray[i], secondAsArray[i]))
{
return false;
}
}
}
return true;
}
private static boolean isCharVisuallyLookingTheSame(char first, char second)
{
// we check if it looks visually the same
for(List<Character> visuallyTheSameList : charactersVisuallyLookingTheSame)
{
boolean doesFirstStringContainVisualChar = false;
for(Character c1 : visuallyTheSameList)
{
if(first == c1)
{
boolean doesSecondStringCharVisuallyEquals = false;
for(Character c2 : visuallyTheSameList)
{
if((second == c2))
{
return true;
}
}
}
}
}
return false;
}
private static void initCharactersThatLookTheSame()
{
// these lists contain all the characters that look visually the same.
// add in here any list of characters that visually look the same.
List<Character> o = new ArrayList<>();
charactersVisuallyLookingTheSame.add(o);
o.add('0');
o.add('o');
o.add('Q');
List<Character> i = new ArrayList<>();
charactersVisuallyLookingTheSame.add(i);
i.add('1');
i.add('I');
i.add('T');
List<Character> z = new ArrayList<>();
charactersVisuallyLookingTheSame.add(z);
z.add('2');
z.add('Z');
List<Character> S = new ArrayList<>();
charactersVisuallyLookingTheSame.add(S);
S.add('5');
S.add('S');
List<Character> B = new ArrayList<>();
charactersVisuallyLookingTheSame.add(B);
B.add('8');
B.add('B');
}
}
Some outputs :
I guess that will do the job. don't hesitate to execute it in debug mode if there are any problems. I fast coded this and I could have made mistakes.
But overall, I suggest you to : use regular expressions. It was suggested by another answer and I think that can only be better than this. Nevertheless, regular expressions can be hard to understand...
The other option would be to build a Map with a common Identifier between similar values. Might be a bit more complicated, but should be more performant than looping a replaceAll multiple times to normalize both values.
import java.util.HashMap;
import java.util.Map;
public class VisuallySimilar
{
public static int id = 0;
public static Map<Character, Integer> map = new HashMap<>();
public static void similarChars(Character... chars) {
for(Character c : chars) {
map.put(c, id);
}
id++;
}
public static boolean areSimilar(String val1, String val2) {
if(val1.length() != val2.length())
return false;
char[] char1 = val1.toCharArray();
char[] char2 = val2.toCharArray();
for(int i = 0; i < char1.length; i++) {
if(char1[i] == char2[i] || map.get(char1[i]) == map.get(char2[i]))
continue;
return false;
}
return true;
}
public static void main(String[] args) {
similarChars('0', 'o', 'O', 'Q');
similarChars('T', 'I', '1');
String val1 = "b0x";
String val2 = "box";
System.out.println("Are Similar: " + areSimilar(val1, val2));
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
Hi I'm trying to build a palindrome but it seem to be not working, please could you help. I'm expected to catch true on dad and false on other things
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter Your User Name");
String userInput =input.nextLine();
System.out.println(abcDEF(userInput));
}
static boolean abcDEF(String userInput) {
StringBuilder s1 = filter(userInput);
StringBuilder s2 = reverse(userInput);
return s1.toString() == s2.toString();
}
static StringBuilder filter(String userInput) {
StringBuilder sb = new StringBuilder();
char[] inputData = userInput.toCharArray();
for (int i = 0; i < userInput.length(); i++) {
if (userInput.matches("[a-zA-Z0-9]+")) {
sb.append(inputData[i]);
}
}
return sb;
}
static StringBuilder reverse(String userInput) {
StringBuilder sb = filter(userInput);
sb.reverse();
return sb;
}
change your abcDEF() to this(last line):
static boolean abcDEF(String userInput) {
StringBuilder s1 = filter(userInput);
StringBuilder s2 = reverse(userInput);
return s1.toString().equals(s2.toString());
}
You are comparing the references of two strings in your code, which is not same in your case. Rather, you should compare the content of the strings. And this is how String contents are compared.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I do have some piece of code, I find unfathomable to comprehend. I save a longer string in a variable and then try to find a specific piece of string inside of it. The clue is that I can output the various substrings, but it will not find the specific string and stop the process...
The code goes like this:
import java.io.*;
import java.util.*;
public class Readin {
public static void main(String[] args) {
String specChar = "DISD";
String gen = "MLRVFILYAENVHTPDTDISDAYCSAVFAGVKKRTKVIKNSVNP";
for (int i = 0; i < gen.length() - 3; i++) {
char char1 = gen.charAt(i);
char char2 = gen.charAt(i + 1);
char char3 = gen.charAt(i + 2);
char char4 = gen.charAt(i + 3);
String concatChar = new StringBuilder().append(char1).append(char2).append(char3).append(char4).toString();
System.out.println(concatChar);
if (specChar == concatChar) {
System.out.println(specChar);
break;
} else {
System.out.println("Error");
}
}
}
}
Short answer: you need to replace (specChar == concatChar) by (Objects.equals(specChar, concatChar)) or (specChar.equals(concatChar)) and you'll come to the break operator
Detailed explanation you can find in articles how to compare strings in Java
After looking at your code, I thought your if should not be for string comparison rather it should be character comparison and condition should be like below in below code. Also I rewrite your code for a actual substring comparison in java as well. :-)
import java.io.*;
import java.util.*;
public class Readin {
public static void main(String[] args) {
String specChar = "DISD";
String gen = "MLRVFILYAENVHTPDTDISDAYCSAVFAGVKKRTKVIKNSVNP";
for (int i = 0; i < gen.length() - 3; i++) {
char char1 = gen.charAt(i);
char char2 = gen.charAt(i + 1);
char char3 = gen.charAt(i + 2);
char char4 = gen.charAt(i + 3);
String concatChar = new StringBuilder().append(char1).append(char2).append(char3).append(char4).toString();
System.out.println(concatChar);
//if (specChar == concatChar) {
//compare each character from 1st to 4th
if (char1 == specChar.charAt(0) && char2 == specChar.charAt(1) && char3 == specChar.charAt(2) && char4 == specChar.charAt(3)) {
System.out.println(specChar);
break;
} else {
System.out.println("Error");
}
}
}
}
Now see the modified one below:-
public class Readin {
public static void main(String[] args) {
String specChar = "DISD";
String gen = "MLRVFILYAENVHTPDTDISDAYCSAVFAGVKKRTKVIKNSVNP";
if (gen.contains(specChar)) {
System.out.println(specChar);
} else {
System.out.println("Error");
}
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I need to read the names from a array list and compare them using loops and print the values from the array in the list
import java.io.*;
import java.util.*;
public class UniqueName {
public static void main(String args[]) throws IOException{
int wordcount = 0;
Scanner input = new Scanner(new FileReader("Names.txt"));
while (input.hasNextLine()) {
String line = input.nextLine();
String str [] = line.split((" "));
for ( int i = 0; i <str.length ; i ++) {
if (str [i].length() > 0) {
wordcount ++;
}
}
}
System.out.println(wordcount);
}
}
Here is what you want:
import java.io.*;
import java.util.*;
public class UniqueName {
public static void main(String args[]) throws IOException{
Scanner input = new Scanner(new FileReader("Names.txt"));
Set<String> uniqueNames = new HashSet<String>();
while (input.hasNextLine()) {
String line = input.nextLine();
String str [] = line.split((" "));
for ( int i = 0; i <str.length ; i ++) {
if (str [i].length() > 0) {
wordcount ++;
}
uniqueNames.add(str[i]);
}
}
System.out.println(wordcount);
System.out.println(uniqueNames);
}
}
Using a set, it only adds the value you pass if it doesn't already exist in it.
Then you can print it out with println(uniqueNames); which will print out each element like so: "[name1, name2, name3, ..., nameN]"
To get rid of the brackets and commas, you can use this:
String str = uniqueNames.toString();
str = str.replace('[', '');
str = str.replace(']', '');
str = str.replace(',', '');
If you want to get each one on a new line, you can change replace(',', '') to: replace(',', '\n');
here you go, try to learn something from it :)
public static void main(String args[]) throws IOException {
Scanner input = new Scanner(new FileReader("names.txt"));
// this is the arraylist to keep all the names from your file
ArrayList<String> names = new ArrayList<String>();
while (input.hasNextLine()) {
// since some of the names have spaces at the end, we pass them
// trough a cleanup method to remove the spaces
String line = clearSpaces(input.nextLine());
// add the cleaned up names to the arraylist
names.add(line);
}
// loop through all the names in the array for comparisson
for (int c = 0; c < names.size(); c++) {
// set each name to be unique until proven otherwise
boolean unique = true;
// take the name out of the array to test
String testString = names.get(c);
// loop through all the other names in the array for comparisson
for (int i = 0; i < names.size(); i++) {
// only if the indexes are different the comparisson makes sense
if (i != c) {
// take the name out of the array to test against
String tempString = names.get(i);
// test the names against each other
if (testString.equals(tempString)) {
// if they are the same then it's not unique
unique = false;
// break the loop cause we already know it's not unique
break;
}
}
}
// only if the unique boolean value is still true
// after testing against all other names
if (unique)
// print the name of that unique name
System.out.println(testString);
}
}
// returns a string clean of spaces
private static String clearSpaces(String withSpaces) {
// string builder for the string output
StringBuilder withoutSpaces = new StringBuilder();
char[] chars = withSpaces.toCharArray();
// loop the array of characters
for (char c : chars) {
// if it's not equal to 32 which corresponds to space char
if (c != 32) {
// append it to the string builder
withoutSpaces.append(c);
}
}
// return all the chars as string
return withoutSpaces.toString();
}
This question already has answers here:
Check string for palindrome
(42 answers)
Closed 7 years ago.
I want to check if a string is a palindrome or not. I would like to learn an easy method to check the same using least possible string manipulations
Using reverse is overkill because you don't need to generate an extra string, you just need to query the existing one. The following example checks the first and last characters are the same, and then walks further inside the string checking the results each time. It returns as soon as s is not a palindrome.
The problem with the reverse approach is that it does all the work up front. It performs an expensive action on a string, then checks character by character until the strings are not equal and only then returns false if it is not a palindrome. If you are just comparing small strings all the time then this is fine, but if you want to defend yourself against bigger input then you should consider this algorithm.
boolean isPalindrome(String s) {
int n = s.length();
for (int i = 0; i < (n/2); ++i) {
if (s.charAt(i) != s.charAt(n - i - 1)) {
return false;
}
}
return true;
}
For the least lines of code and the simplest case
if(s.equals(new StringBuilder(s).reverse().toString())) // is a palindrome.
Here is a simple one"
public class Palindrome {
public static void main(String [] args){
Palindrome pn = new Palindrome();
if(pn.isPalindrome("ABBA")){
System.out.println("Palindrome");
} else {
System.out.println("Not Palindrome");
}
}
public boolean isPalindrome(String original){
int i = original.length()-1;
int j=0;
while(i > j) {
if(original.charAt(i) != original.charAt(j)) {
return false;
}
i--;
j++;
}
return true;
}
}
You can try something like this :
String variable = ""; #write a string name
StringBuffer rev = new StringBuffer(variable).reverse();
String strRev = rev.toString();
if(variable.equalsIgnoreCase(strRev)) # Check the condition
Here's a good class :
public class Palindrome {
public static boolean isPalindrome(String stringToTest) {
String workingCopy = removeJunk(stringToTest);
String reversedCopy = reverse(workingCopy);
return reversedCopy.equalsIgnoreCase(workingCopy);
}
protected static String removeJunk(String string) {
int i, len = string.length();
StringBuffer dest = new StringBuffer(len);
char c;
for (i = (len - 1); i >= 0; i--) {
c = string.charAt(i);
if (Character.isLetterOrDigit(c)) {
dest.append(c);
}
}
return dest.toString();
}
protected static String reverse(String string) {
StringBuffer sb = new StringBuffer(string);
return sb.reverse().toString();
}
public static void main(String[] args) {
String string = "Madam, I'm Adam.";
System.out.println();
System.out.println("Testing whether the following "
+ "string is a palindrome:");
System.out.println(" " + string);
System.out.println();
if (isPalindrome(string)) {
System.out.println("It IS a palindrome!");
} else {
System.out.println("It is NOT a palindrome!");
}
System.out.println();
}
}
Enjoy.
public boolean isPalindrom(String text) {
StringBuffer stringBuffer = new StringBuffer(text);
return stringBuffer.reverse().toString().equals(text);
}
I guess this is simple way to check palindrome
String strToRevrse = "MOM";
strToRevrse.equalsIgnoreCase(new StringBuilder(strToRevrse).reverse().toString());
I'm new to java and I'm taking up your question as a challenge to improve my knowledge as well so please forgive me if this does not answer your question well:
import java.util.ArrayList;
import java.util.List;
public class PalindromeRecursiveBoolean {
public static boolean isPalindrome(String str) {
str = str.toUpperCase();
char[] strChars = str.toCharArray();
List<Character> word = new ArrayList<>();
for (char c : strChars) {
word.add(c);
}
while (true) {
if ((word.size() == 1) || (word.size() == 0)) {
return true;
}
if (word.get(0) == word.get(word.size() - 1)) {
word.remove(0);
word.remove(word.size() - 1);
} else {
return false;
}
}
}
}
If the string is made of no letters or just one letter, it is a
palindrome.
Otherwise, compare the first and last letters of the string.
If the first and last letters differ, then the string is not a palindrome
Otherwise, the first and last letters are the same. Strip them from the string, and determine whether the string that remains is a palindrome. Take the answer for this smaller string and use it as the answer for the original string then repeat from 1.
The only string manipulation is changing the string to uppercase so that you can enter something like 'XScsX'
check this condition
String string="//some string...//"
check this...
if(string.equals((string.reverse())
{
it is palindrome
}
public static boolean istPalindrom(char[] word){
int i1 = 0;
int i2 = word.length - 1;
while (i2 > i1) {
if (word[i1] != word[i2]) {
return false;
}
++i1;
--i2;
}
return true;
}
import java.util.Scanner;
public class FindAllPalindromes {
static String longestPalindrome;
public String oldPalindrome="";
static int longest;
public void allSubstrings(String s){
for(int i=0;i<s.length();i++){
for(int j=1;j<=s.length()-i;j++){
String subString=s.substring(i, i+j);
palindrome(subString);
}
}
}
public void palindrome(String sub){
System.out.println("String to b checked is "+sub);
StringBuilder sb=new StringBuilder();
sb.append(sub); // append string to string builder
sb.reverse();
if(sub.equals(sb.toString())){ // palindrome condition
System.out.println("the given String :"+sub+" is a palindrome");
longestPalindrome(sub);
}
else{
System.out.println("the string "+sub+"iss not a palindrome");
}
}
public void longestPalindrome(String s){
if(s.length()>longest){
longest=s.length();
longestPalindrome=s;
}
else if (s.length()==longest){
oldPalindrome=longestPalindrome;
longestPalindrome=s;
}
}
public static void main(String[] args) {
FindAllPalindromes fp=new FindAllPalindromes();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String ::");
String s=sc.nextLine();
fp.allSubstrings(s);
sc.close();
if(fp.oldPalindrome.length()>0){
System.out.println(longestPalindrome+"and"+fp.oldPalindrome+":is the longest palindrome");
}
else{
System.out.println(longestPalindrome+":is the longest palindrome`````");
}}
}