How to separate many different words from a string (Java) - java

I've been struggling to figure out how to get a word, of unknown length, from a string, of unknown length, that I'm reading from a file. The words I want from the string are always separated by "." and/or "&" with the whole string being surrounded by quotes. EX: ".Word.Characters&Numeric&Letters.Typos&Mistypes." I know the location of each "." and "&" as well as how many times they occur.
I want to feed the words into an array Example[i][j] based on whether or not the words are separated by a "." or a "&". So words contained between "." would be set into the i column of the array and words linked by "&" into the j rows of the array.
The input string can contain a largely variable number of words. Meaning that there can be only one word of interest, or one hundred+.
I'd prefer to use arrays to solve this problem. From what I've read regex would be slow, but work. split() may also work, but I think I'd have to know what words to look for before hand.
From this String: ".Word.Characters&Numeric&Letters.Typos&Mistypes." I'd expect to get: (without worrying about which is a row or column)
[[Word],[null],[null]],
[[Characters],[Numbers],[Letters]],
[[Typos],[Mistypes],[null]]
From this String ".Alpha.Beta.Zeta&Iota." I'd expect to get:
[[Alpha],[null]],
[[Beta],[null]],
[[Zeta],[Iota]]
//NumerOfPeriods tells me how many word "sections" are in the string
//Stor[] is an array that holds the string index locations of "."
for(int i=0;i<NumberOfPeriods;i++)
{
int length = Stor[i];
while(Line.charAt(length) != '"')
{
length++;
}
Example[i] = Line.substring(Stor[i], length);
}
//This code can get the words separated by "." but not by "&"
//Stor[] is an array that holds all string index locations of '.'
//AmpStor[] is an array that holds all string index locations of '&'
int TotalLength = Stor[0];
int InnerLength = 0;
int OuterLength = 0;
while(Line.charAt(TotalLength) != '"')
{
while(Line.charAt(OuterLength)!='.')
{
while(Line.charAt(InnerLength)!='&')
{
InnerLength++;
}
if(Stor[i] > AmpStor[i])
{
Example[i][j] = Line.substring(Stor[i], InnerLength);
}
if(Stor[i] < AmpStor[i])
{
Example[i][j] = Line.substring(AmpStor[i],InnerLength);
}
OuterLength++;
}
}
//Here I run into the issue of indexing into different parts of the array i & j

This is how I would solve your problem (it's completely different from your code but it works).
First of all, remove the quotes and the leading and trailing non-word characters. This can be done using replaceAll:
String Formatted = Line.replaceAll( "(^\"[.&]*)|([.&]*\"$)", "" );
The regular expression in the first argument will match the double quotes at both ends and the leading and trailing .s and &s. The method will return a new string where the matched characters are removed, because the second argument is an empty string (it replaces with an empty string).
Now you can split this string at each . using the split method. You could only define your output array after this call:
String[] StringGroups = Formatted.split( "\\." );
String[][] Elements = new String[StringGroups.length][];
Use an escaped backslash (\\) before the point to indicate that it should split on .-characters, since this method takes in a regular expression (and just . splits on any non-newline character).
Now split each string in that array at each & using the same split method. Add the result directly to your Elements array:
// Loop over the array
int MaxLength = 0;
for( int i = 0; i < StringGroups.length; i ++ ) {
String StrGroup = StringGroups[ i ];
String[] Group = StrGroup.split( "&" );
Elements[ i ] = Group;
// Measure the max length
if( Group.length > MaxLength ) {
MaxLength = Group.length;
}
}
A \\ is not necessary for the input, since & just matches &-characters. Now you only have to fill in your data into an array. The MaxLength variable is for adding the null values to your array. If you don't want them, just remove them and you're done here.
If you want the null values however, loop over your elements array and copy the current rows into new arrays:
for( int i = 0; i < Elements.length; i ++ ) {
String[] Current = Elements[ i ];
String[] New = new String[ MaxLength ];
// Copy existing values into new array, extra values remain null
System.arraycopy( Current, 0, New, 0, Current.length );
Elements[ i ] = New;
}
Now, the Elements array contains exactly what you wanted.
Here is the complete executable code:
public class StringSplitterExample {
public static void main( String[] args ) {
test( "\".Word.Characters&Numeric&Letters.Typos&Mistypes.\"" );
System.out.println(); // Line between
test( "\".Alpha.Beta.Zeta&Iota.\"" );
}
public static void test( String Line ) {
String Formatted = Line.replaceAll( "(^\"[.&]*)|([.&]*\"$)", "" );
String[] StringGroups = Formatted.split( "\\." );
String[][] Elements = new String[StringGroups.length][];
// Loop over the array
int MaxLength = 0;
for( int i = 0; i < StringGroups.length; i ++ ) {
String StrGroup = StringGroups[ i ];
String[] Group = StrGroup.split( "&" );
Elements[ i ] = Group;
// Measure the max length
if( Group.length > MaxLength ) {
MaxLength = Group.length;
}
}
for( int i = 0; i < Elements.length; i ++ ) {
String[] Current = Elements[ i ];
String[] New = new String[ MaxLength ];
// Copy existing values into new array, extra values remain null
System.arraycopy( Current, 0, New, 0, Current.length );
Elements[ i ] = New;
}
for( String[] Group : Elements ) {
for( String String : Group ) {
System.out.print( String );
System.out.print( " " );
}
System.out.println();
}
}
}
The output of this example:
Word null null
Characters Numeric Letters
Typos Mistypes null
Alpha null
Beta null
Zeta Iota
So this works, and you don't even need to know where the . and & characters are in your string. Java will just do that for you.

If I understand the problem correctly, you want to separate the string into substrings delimited by '.' and then for each of the substrings, separate it into subsubstrings delimited by '&'. If that's the case, then I would use the split method:
List<List<String>> terms = Arrays.stream(input.split("\\."))
.map(s -> Arrays.asList(s.split("\\&"))
.collect(Collectors.toList());
if you really need it to be returned as a null-padded array:
String[][] result = new String[terms.size()][ terms.stream.mapToInt(List::size).max().getAsInt()];
IntStream.range(0, terms.size()).forEach(i ->
IntStream.range(0, terms.get(i).size()).forEach(j ->
result[i][j] = terms.get(i).get(j)));

Here is how I tried to solve the problem:
import java.util.*;
import java.util.stream.*;
public class StringSplitSplits {
private static final String S1 = ".Word.Characters&Numeric&Letters.Typos&Mistypes.";
private static final String S2 = ".Alpha.Beta.Zeta&Iota.";
public static void main(String [] args) {
String str = stripStartAndEndDots(S1);
String [] ss = str.split("\\.");
int maxLength = getMaxLength(ss);
String [][] sss = Stream.of(ss)
.map(s -> s.split("&"))
.map(s -> Arrays.copyOf(s, maxLength))
.toArray(String[][]::new);
Stream.of(sss).forEach(s -> System.out.println(Arrays.toString(s)));
}
private static String stripStartAndEndDots(String input) {
if (input.startsWith(".")) {
input = input.substring(1);
}
if (input.endsWith(".")) {
input = input.substring(0, input.length()-1);
}
return input;
}
/*
* Get max length of the arrays split on the "&" for each
* string element of the input string array.
*/
private static int getMaxLength(String [] input) {
return Stream.of(input)
.map(s -> s.split("&"))
.mapToInt(ss -> ss.length)
.max()
.orElse(0);
}
}
Input: ".Word.Characters&Numeric&Letters.Typos&Mistypes."
Output:
[Word, null, null]
[Characters, Numeric, Letters]
[Typos, Mistypes, null]
Input: ".Alpha.Beta.Zeta&Iota."
Output:
[Alpha, null]
[Beta, null]
[Zeta, Iota]

Related

Java Comparing characters in strings and counting the similarities

my question is asking this:
Write a program that compares two input strings. Output the number of characters that match in each string position. The output should use the correct verb (match vs matches) according to the character count.
Ex: If the input is:
crush crash
the output is:
4 characters match
this is what i have so far:
import java.util.Scanner;
public class LabProgram
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String str1 = in.next();
String str2 = in.next();
int counter=0;
if(str1.indexof(0)==str2.indexof(0)){
counter++;
System.out.println(counter+"character match");
else
System.out.println("All characters match");
}
}
I know it doesn't look like a lot but I've tried this so many other ways but I clearly am missing something that would make this easier to do. I wanted to count the similar letters in my counter...but I don't know what to do.
Use a for loop to iterate across the string inputs and utilize charAt() to look at specific characters within a string
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str1 = in.next();
String str2 = in.next();
int counter=0;
// Loop across the smaller input string
// Math.min gives us the lesser of 2 values
for (int i = 0; i < Math.min(str1.length(), str2.length()); i++){
// If two characters match
if (str1.charAt(i) == str2.charAt(i)){
// Increment counter
counter++;
}
}
// If counter = length of both strings
if (counter == str1.length() && counter == str2.length()){
System.out.println("All characters match");
// If counter is 1
} else if (counter == 1){
System.out.println("1 character matches");
// Otherwise
} else {
System.out.println(counter + " characters match");
}
}
Note: To use Math.Min(), you'll need to
import java.lang.Math;
It's not completely necessary though; you could just figure out which string is longer on your own
Code point
Avoid using char. That type is essentially broken since Java 2, legacy since Java 5. As a 16-bit value, char is physically incapable of representing most characters. One emoji could ruin your whole day.
Instead, use code point integer numbers when working with individual characters. You’ll find code point related methods on several classes, including String, StringBuilder, and Character.
int[] codePointsX = x.codePoints().toArray() ;
int[] codePointsY = y.codePoints().toArray() ;
First, check lengths.
boolean sameLength = ( codePointsX.length == codePointsY.length ) ;
if ( ! sameLength ) { … }
Create an array to hold results of comparing each character.
int[] results = new int[ codePointsX.length ] ;
Compare. The ternary operator ?: is a condensed alternative to using an if test.
We put a zero into results array if the two code points match. Else, we put a zero into results array. The default is a zero, so we could skip the assignment of zero. But I want our intentions to be crystal clear to the reader.
for( int index = 0 ; index < codePointsX.length ; index ++ )
{
results[ index ] =
codePointsX[ index ] == codePointsY[ index ] ? 1 : 0 ; // One for a matching character, Zero for a mismatch.
}
Results.
int countMatches = Arrays.stream( results ).sum();
Full example code.
String x = "cat" ;
String y = "cot" ;
int[] codePointsX = x.codePoints().toArray() ;
int[] codePointsY = y.codePoints().toArray() ;
boolean sameLength = ( codePointsX.length == codePointsY.length ) ;
if ( ! sameLength ) {
throw new IllegalArgumentException( "The two input strings have different lengths. " ) ;
}
int[] results = new int[ codePointsX.length ] ;
for( int index = 0 ; index < codePointsX.length ; index ++ )
{
results[ index ] =
codePointsX[ index ] == codePointsY[ index ] ? 1 : 0 ;
}
int countMatches = Arrays.stream( results ).sum();
System.out.println( Arrays.toString( results ) ) ;
System.out.println( "countMatches = " + countMatches ) ;
See this code run at Ideone.com.
[1, 0, 1]
countMatches = 2

How to append String to StringBuffer variable in JAVA

My code is as below. i need to add single quotes for each word in string with single quotes after appending DD to it.
public class Main
{
public static void main(String[] args) {
String ChkboxIds = "'a1b2c3','321cba','123abc'";
String checkBoxId = null;
String checkId = null;
StringBuilder checkIDS = new StringBuilder("'");
for(int i=0;i<=ChkboxIds.split(ChkboxIds, ',').length;i++){
checkBoxId = "DD"+ChkboxIds.split(",")[i].replace("'","")+","+checkBoxId;
checkId = checkBoxId.substring(0, checkBoxId.length() - 5);
System.out.println("---PRINT---"+checkId);
for(int j=0;j<i;j++){
checkIDS..append('\'').append(checkId.split(",")).append('\'').append(',');
System.out.println("---PRINT123----"+checkIDS);
}
}
}
}
I have tried using StringBuffer too. please point your answers here. The output i get is some junk data while i need the words with dd attached at the start.
Expected output:'DDa1b2c3','DD321cba','DD123abc'
Problem
issue at .append(checkId.split(",")) where you append an String[] so it's representation is it's hashcode
don't need a second loop, each word need one loop round, no inner loop needed
your split is wrong, you need ChkboxIds.split(","), you don't need with the same string as delimiter
Fix
You can do much more simpler than that
split on comma
remove quotes, append DD, add quotes
save at same place in array
join array with comma
String chkboxIds = "'a1b2c3','321cba','123abc'";
String[] splitted = chkboxIds.split(",");
String checkBoxId;
for (int i = 0; i < splitted.length; i++) {
checkBoxId = "DD" + splitted[i].replace("'", "");
splitted[i] = "'" + checkBoxId + "'";
}
String result = String.join(",", splitted);
System.out.println(result);
// 'DDa1b2c3','DD321cba','DD123abc'
Regex power
String chkboxIds = "'a1b2c3','321cba','123abc'";
String result = chkboxIds.replaceAll("'(\\w+)'", "'DD$1'");
Try this:
var ids = Arrays.stream( ChkboxIds.split( "," ) ) // Separate the words
.map( s -> s.replace( '\'', '' ) ) // Strip the single quotes
.map( s -> "DD%s".formatted( s ) ) // Prepend with "DD"
.collect( Collectors.joining( "','", "'", "'" ) );
System.out.println( ids );
Alternatively:
var ids = Arrays.stream( ChkboxIds.split( "," ) ) // Separate the words
.map( s -> s.replaceFirst( "'", "'DD" ) ) // Replace the first single quote with the prefix
.collect( Collectors.joining( "," ) );
System.out.println( ids );
Refer to the respective Javadoc for the details.
For a simpler solution, you can try the code below.
public class Main
{
public static void main(String[] args) {
String ChkboxIds = "'a1b2c3','321cba','123abc'";
//Replace all single quotes from the ChkboxIds, split them using comma delimiter, and store it to variable array
String[] ChkboxIdsNew = ChkboxIds.replace("'","").split(",");
String checkIDS = ""; //String variable to be used to store the check ids
//Loop through the ChkboxIdsNew array
for (int i = 0; i < ChkboxIdsNew.length; i++) {
//Only append comma if i is greater than zero
if (i > 0) {
checkIDS = checkIDS + ",";
}
//Concatenate the single quotes and prefix DD then append it to checkIDS
checkIDS = checkIDS + "'DD" + ChkboxIdsNew[i] + "'";
}
System.out.println(checkIDS);
}
}
Output:
Using regular expressions:
If the single words doesnt contain additional single quotes:
String ChkboxIds = "'a1b2c3','321cba','123abc'";
ChkboxIds = ChkboxIds.replaceAll(",'",",'DD").replaceAll("^'","'DD");
Using iteration :
String arChkBoxIds[]= ChkboxIds.split(",");
StringBuilder checkIDS1 = new StringBuilder("");
for (String chkBoxId:arChkBoxIds){
checkIDS1.append("'DD").append(chkBoxId.substring(1)).append(",");
}
checkIDS1.setLength(checkIDS1.length()-1);
System.out.println(checkIDS1);

How to delete every 12th character from a string in java

Lets say I have a string like this:
String str = "~asdfl;kjx,~rgadfaeg,dsafnewgfljka;ldfjsfa;dlkjfa;lvjvbnaber;fwelfjadfafa"
int character = 12
What I want to do is delete every 12th character in the string, so i would delete the 12 index, then the 24th, then the 36th, etc until the string is over.
Which index I delete (every 12th, or every 2nd) has to equal the character variable I have, since that variable changes.
I tried doing this with regex:
System.out.println(s.replaceAll(".(.)", "$12"));
But it didnt work. any help?
Sometimes, a simple for loop is all you need:
public class Test {
public static void main(String[] args) {
String str = "~asdfl;kjx,~rgadfaeg,dsafnewgfljka;ldfjsfa;dlkjfa;lvjvbnaber;fwelfjadfafa";
int character = 12;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if ((i + 1) % character != 0) {
sb.append(str.charAt(i));
}
}
String result = sb.toString();
System.out.println(result);
}
}
If you insist on using regular expressions, you can interpolate the character variable into the expression as follows:
public class Test {
public static void main(String[] args) {
String str = "~asdfl;kjx,~rgadfaeg,dsafnewgfljka;ldfjsfa;dlkjfa;lvjvbnaber;fwelfjadfafa";
int character = 12;
System.out.println(str.replaceAll("(.{" + (character - 1) + "}).", "$1"));
}
}
To delete every 12th character using regex, use this pattern:
(.{11}).
And then replace with just the captured $1.
Sample Java code:
String str = "~asdfl;kjx,~rgadfaeg,dsafnewgfljka;ldfjsfa;dlkjfa;lvjvbnaber;fwelfjadfafa";
String output = str.replaceAll("(.{11}).", "$1");
System.out.println(output);
This prints:
~asdfl;kjx,rgadfaeg,dsfnewgfljka;dfjsfa;dlkja;lvjvbnabe;fwelfjadfaa
Edit:
To do a regex replacement of some fixed width, use:
String str = "~asdfl;kjx,~rgadfaeg,dsafnewgfljka;ldfjsfa;dlkjfa;lvjvbnaber;fwelfjadfafa";
int width = 11;
String output = str.replaceAll("(.{" + width + "}).", "$1");
System.out.println(output);
Avoid char
The char type in Java is legacy, essentially broken. As a 16-bit value, a char is incapable of representing most characters.
Code points
Instead, use code point integers.
Make an array of each character’s code point.
int[] codePointsArray = input.codePoints().toArray() ;
Make a list of that array.
List< Integer > codePoints = List.of( codePointsArray ) ;
Alternatively:
List< Integer > codePoints = input.codePoints().boxed().toList() ;
Make an IntStream of the indexes we need to access each element of that list. Use each index to pull out a code point, and filter by the nth element. Collect into a StringBuilder.
String result =
IntStream
.range( 0 , codePoints.size() )
.filter( n -> n % 12 != 0 )
.mapToObj( codePoints :: get )
.collect( StringBuilder :: new , StringBuilder :: appendCodePoint , StringBuilder :: append )
.toString()
;
That is untested code, but should be close to what you need.
My code here is based on what I saw on this similar Question.

Assign unique int values to a word in a String then store it into an Array

I'm trying to get the unique words within a string then storing it within an array along with the amount of times it occurs.
My approach towards this was to assign a unique integer to each unique string within an if-else statement, then taking the unique counts of those integers, and pulling any one word from the string that's assigned a unique value, and finally taking the number of times the unique integer occurs.
However, whenever I get to assigning a unique value to the String I get null:
import java.util.Arrays;
public class StringLearning {
public static void main(String[] args) {
final String text = "Win Win Win Win Draw Draw Loss Loss";
int[] numbers = null;
if(text.equals("Win")) {
numbers= new int[1];
}else if(text.equals("Draw")){
numbers = new int [2];
}else if(text.equals("Loss")) {
numbers = new int [3];
}
System.out.println(Arrays.toString(numbers));
}
}
Expected output:
{1, 1, 1, 1, 2, 2, 3, 3}
EDIT:
How could this be implemented in a general sense? Such that, I did not know the String had "Win, Loss, Draw" in the string, but I'd want to assign a unique integer to any given unique word?
you have many problems with your code.
first, you have to get each word of the string individual, so you need to split it into array.
second, you need to create one array, and in it to put the integers. (what you did is to create new array for each number)
I tried to fix the problems. hope you understand my code.
(I only fixed your code, and not make it generial)
String[] arr = text.split(" ");
int[] numbers = new int[arr.length];
for (int i=0;i<arr.length;i++){
if(arr[i].equals("Win")) {
numbers[i] = 1;
}else if(arr[i].equals("Draw")){
numbers[i] = 2;
}else if(arr[i].equals("Loss")) {
numbers[i] = 3;
}
}
When creating an object of an array, the number in the brackets new int[1] you declare the length of the array. I'd recommend using a HashMap for that matter. An example of code would be:
public class StringLearning {
public static void main(String[] args) {
final String text = "Win Win Win Win Draw Draw Loss Loss";
HashMap<String, Integer> counts = new HashMap<String, Integer>();
for (String word : text.split(" ")) { // loops through each word of the string
// text.split(" ") returns an array, with all the parts of the string between your regexes
// if current word is not already in the map, add it to the map.
if (!counts.containsKey(word)) counts.put(word, 0);
counts.put(word, counts.get(word) + 1); // adds one to the count of the current word
}
// lambda expression
counts.forEach((string, integer) -> System.out.printf("amount of \"%s\": %d\n", string, integer));
}
}
Output:
amount of "Draw": 2
amount of "Loss": 2
amount of "Win": 4
Edit (response to tQuadrat):
I edited this post to keep everything clean and readable.
public class StringLearning {
public static void main(String[] args) {
final String text = "Win Win Win Win Draw Draw Loss Loss";
HashMap<String, Integer> counts = new HashMap<String, Integer>();
for (String word : text.split(" ")) { // loops through each word of the string
// text.split(" ") returns an array, with all the parts of the string between your regexes
// if current word is not already in the map, add it to the map.
if (!counts.containsKey(word))
counts.put(word, counts.size() + 1); // index of the word (+ 1 because your expected output was 1-indexed)
}
for (String word : text.split(" ")) {
System.out.print(counts.get(word) + " ");
}
}
}
Output:
1 1 1 1 2 2 3 3
Let's try this approach:
Get the number of words in the String: var words = text.split( " " ); This assumes that words are separated by blanks only.
Create registry for the words: Map<String,Integer> registry = new HashMap<>();
Create the result array: var result = new int [words.length];
Now loop over the words and check if you have seen the word already:
for( var i = 0; i < words.length; ++i )
{
result [i] = registry.computeIfAbsent( words [i], $ -> registry.size() + 1 );
}
Finally, print the result: System.out.println( Arrays.toString( result ) ); – although this would use […] instead of {…}.
registry.computeIfAbsent( words [i], $ -> registry.size() + 1 ); adds a new entry to the registry for each unseen word and assigns the size of the registry plus one as the unique number for that word. For already known words, it returns the previously assigned number.
This works for any set of words in text.
So the complete thing may look like this:
public final class StringLearning
{
public static final void main( final String... args )
{
final var text = "Win Win Win Win Draw Draw Loss Loss"; // … or any other text
final var words = text.split( " " );
final Map<String,Integer> registry = new HashMap<>();
final var result = new int [words.length];
for( var i = 0; i < words.length; ++i )
{
result [i] = registry.computeIfAbsent( words [i], $ -> registry.size() + 1 );
}
System.out.println( Arrays.toString( result ) );
}
}
Maintain the unique value for each word of string in map and then fetch the unique value while assigning your array.
String text = "Win Win Loss Draw Hello";
String[] split = text.split(" ");
// To maintain unique value for each word of input string
Map<String, Integer> = new HashMap<>();
int counter = 0;
for(String ele:split)
if(!map.containsKey(ele))
map.put(ele, ++counter)
// Getting unique value for each word and assigining in array
int[] array=new int[split.length];
for(int i=0; i<split.length;i++)
array[i] = map.get(split[i]);

how to search for keywords in strings

I need to do some keywords search and print if true.
works fine if i am comparing in order. but i want to
compare the following cases and expect them to be true.
do some java programming = true
some java = true
do programming = true
and finally most importantly
programming java = true
programming java some do = true
I need to return true for all the cases mentioned above but so far it only works for case 1 and 2
public class Examples {
public static void main(String[] args) {
String[] given = new String[20];
given[0] = ("do some java programming");
given[1] = ("do some grocery shopping");
given[2] = ("play soccer at the west field");
String input = new String();
Scanner userInput = new Scanner(System.in);
System.out.println("Enter the string to compare");
input[0] = userInput.nextLine();
for (int i=0; i <20; i++){
if(given[i].contains(input))
{
System.out.println(given[i]);
}
else
{
//do nothing
}
}
}
}
Outline of one way to solve this:
Each string in given should be converted to a Set<String> that is a set of all the words in the string. Use split() on each string to get the words, then go through the list of words and add each word to the Set.
For each input string, use split() to split it into words, then create any kind of collection (a Set<String> will work, but creating a List<String> by using Arrays.asList works too.
You can then see if the collection of words from the input is a subset of the set of words in each given string by using a Set's containsAll method.
(Note that you'll have to make sure the input string isn't the empty set first. Also, if the input string has more than one occurrence of any word, this approach won't catch that, without some extra logic.)
For this Regex will be your friend.
Here's some working code to play with:
String[] matches = input[0].split(" ");
for (int i=0; i <3; i++){
for(String s: matches){
if(given[i].contains(s))
System.out.println(given[i]);
break;
}
}
}
Split the given lines and store it in a List.
Again split the input line and compare word by word.
Below is the code snippet
public class StringCompare
{
public static final String delimiter = " ";
public static void main( String[] args )
{
String[] given = new String[20];
given[ 0 ] = ( "do some java programming" );
given[ 1 ] = ( "do some grocery shopping" );
given[ 2 ] = ( "play soccer at the west field" );
List< List< String >> listLineAsWords = new ArrayList< List< String >>();
//split each line and store it as list.
for ( String line : given )
{
if ( line == null )
break;
listLineAsWords.add( Arrays.asList( line.split( delimiter ) ) );
}
//Write your own logic to get the input line
String inputLine = "programming java";
if ( compareLine( inputLine, listLineAsWords ) )
System.out.println( "The input line is part of given lines" );
}
private static boolean compareLine( String inputLine, List< List< String >> listLineAsWords )
{
if ( inputLine == null )
return false;
List< String > words = Arrays.asList( inputLine.split( delimiter ) );
for ( List< String > listOfWords : listLineAsWords )
{
boolean isPartOfLine = true;
for ( String word : words )
{
if ( !listOfWords.contains( word ) )
{
isPartOfLine = false;
break;
}
}
if(isPartOfLine)
return true;
}
return false;
}
}
Your code is almost right, yet it needs some changes
First, since in your sample code you have 3 case, it is best to define your given array length 3.
String[] given = new String[3];
Note: for more cases, you can define bigger array length; for example, if you will add other 2 cases, your array length is 5
For all reference types, the default value is null if you have array length more than you need.
read more about it here
Second, in your if statement, you want to check if input contains given element of array or not
if (input.contains(given[i])) {
code:
String[] given = new String[3];
given[0] = ("do some java programming");
given[1] = ("do some grocery shopping");
given[2] = ("play soccer at the west field");
Scanner userInput = new Scanner(System.in);
System.out.println("Enter the string to compare");
String input = userInput.nextLine();
for (int i = 0; i < given.length; i++) {
if (input.contains(given[i])) {
System.out.println(given[i]);
} else {
// System.out.println("do nothing");
}
}
output:
Modify as below assuming everything else is fine
//here initialize 'given' array
//get the user input in a string that is 'input[0]' in your case
int count = 0;
for (String s : given) {
if (s != null && s.matches(input[0])) {
//it matches and print it
} else {
//either it's not a match or the 'given' array has a null at this index
}
count++;
}
I must say, get the user input in a string. I don't understand why you have it in input array.

Categories