How to parse and compare text? - java

The problem is that it must compare two Strings (example in a text file), and show the differences in it.
Should in the output also be printed out the equals Elements ?
Instead of using for loops, maybe there are different solutions to reach it.
How can it be done ?
Code
import java.util.ArrayList;
public class ParseTest {
String saR1 = "This is a Test for checking the content and a Test to compare it";
String saR2 = "This is the second Test for checking the seconds content and a second Test to compare it";
String diff1 = "";
String diff2 = "";
int o3;
int o4;
public static void main(String[] args) {
new ParseTest().parseMethod();
}
private void parseMethod() {
String[] sa1 = saR1.split("\\s");
String[] sa2 = saR2.split("\\s");
ArrayList<String> al1 = new ArrayList<String>();
ArrayList<String> al2 = new ArrayList<String>();
for(int o = 0; o<sa1.length; o++) {
al1.add(sa1[o]);
}
for(int o = 0; o<sa2.length; o++) {
al2.add(sa2[o]);
}
if(al1.size() <= al2.size()) {
for(int oi = 0; oi<al2.size()+al1.size(); oi++) {
for(o4 = 0; o4<al2.size(); o4++) {
for(o3 = 0; o3<al1.size(); o3++) {
if(al1.size() == al2.size() && al2.get(o4).equalsIgnoreCase(al1.get(o3))) {
al1.remove(al1.get(o3));
al2.remove(al2.get(o4));
}
if(al2.size() > al1.size() && al2.get(o4).equalsIgnoreCase(al1.get(o3))) {
al1.remove(al1.get(o3));
al2.remove(al2.get(o4));
}
}
}
}
}
for(String or1 : al1) {
diff1 += " " + or1;
} System.out.println("This is saR1 :" + saR1);
System.out.println("This is the difference in saR1 :" + diff1);
for(String or2 : al2) {
diff2 += " " + or2;
} System.out.println("This is saR2 :" + saR2);
System.out.println("This is the difference in saR2 :" + diff2);
}}

A possible solution :
package parsetest;
import java.util.ArrayList;
public class ParseTest {
String saR1 = "This is a Test for checking the content and a Test to compare it";
String saR2 = "This is the second Test for checking the seconds content and a second Test to compare it";
String diff1 = "";
String diff2 = "";
int o3;
int o4;
public static void main(String[] args) {
new ParseTest().parseMethod();
}
private void parseMethod() {
String[] sa1 = saR1.split("\\s"); // split into single words
String[] sa2 = saR2.split("\\s");
ArrayList<String> al1 = new ArrayList<String>(); // create ArrayList with more methods to manipulate, avaiable from the api
ArrayList<String> al2 = new ArrayList<String>();
for(int o = 0; o<sa1.length; o++) { // adding single elements of array[] to ArrayList
al1.add(sa1[o]);
}
for(int o = 0; o<sa2.length; o++) {
al2.add(sa2[o]);
}
if(al1.size() <= al2.size()) {
for(int oi = 0; oi<al2.size()+al1.size(); oi++) {
for(o4 = 0; o4<al2.size(); o4++) {
for(o3 = 0; o3<al1.size(); o3++) {
if(al1.size() == al2.size() && al2.get(o4).equalsIgnoreCase(al1.get(o3))) {
al1.remove(al1.get(o3));
al2.remove(al2.get(o4));
}
if(al2.size() > al1.size() && al2.get(o4).equalsIgnoreCase(al1.get(o3))) {
al1.remove(al1.get(o3));
al2.remove(al2.get(o4));
}
}
}
}
}
for(String or1 : al1) { // walking thru the arraylists with remaining elements and printing out results
diff1 += " " + or1;
} System.out.println("This is saR1 :" + saR1);
System.out.println("This is the difference in saR1 :" + diff1);
for(String or2 : al2) {
diff2 += " " + or2;
} System.out.println("This is saR2 :" + saR2);
System.out.println("This is the difference in saR2 :" + diff2);
}}

Related

How can i have output that write different or missing element in array?

When I run this, I can see exact result "false" but I also want to see what difference there is. For instance
"ozer and gunthy" match but "albundy and aldy" does not
package start;
public class Start {
public static void main(String[] args) {
String[] a = {"ozer + gunthy + albundy"};
String[] b = {"ozer + günthy + aldy"};
boolean b1 = false;
if (a.length != b.length){
b1 = false;
}else {
for (int i = 0; i < a.length; i++){
if (a[i] == b[i]){
b1 = true;
}else {
b1 = false;
break;
}
}
}
System.out.println(b1);
}
}
You will want to replace
a[i] == b[i]
with
a[i].equals(b[i])
You will also need to fix your arrays
public static String[] list1 = {"ozer", "gunthy","albundy"};
public static String[] list2 = {"ozer", "günthy","aldy"};
then, you will need to write and call a method to properly analyze the arrays to your specification:
public String methodName(String[] list1, String[] list2)
{
String output = "";
if (list1.length != list2.length)
{
return "The Arrays differ in length";
}
else
{
for (int i = 0; i < list1.length; i++)
{
if (list1[i].equals(list2[i]))
{
output += "" + list1[i] + " is equal to " + list2[i] + "\n";
}
else
{
output += "" + list1[i] + " is not equal to " + list2[i] + "\n";
}
}
}
return output;
}

What is wrong with this swapping program in Java, why and what should I do?

I am making a multiple string input random swap without using a temp variable.
But when I input, this happens a few times:
This happens more frequently... (note that the first output is always null and some outputs occasionally repeat)
My code:
import java.util.Arrays;
import java.util.Scanner;
public class myFile {
public static boolean contains(int[] array, int key) {
Arrays.sort(array);
return Arrays.binarySearch(array, key) >= 0;
}
public static void println(Object line) {
System.out.println(line);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String finalText = "";
String[] input = new String[5];
String[] swappedInput = new String[input.length];
int[] usedIndex = new int[input.length];
int swapCounter = input.length, useCounter;
for (int inputCounter = 0; inputCounter < input.length; inputCounter++) { //input
println("Enter input 1 " + (inputCounter + 1) + ": ");
input[inputCounter] = in.nextLine();
}
while (--swapCounter > 0) {
do{
useCounter = (int) Math.floor(Math.random() * input.length);
}
while (contains(usedIndex, useCounter));
swappedInput[swapCounter] = input[swapCounter].concat("#" + input[useCounter]);
swappedInput[useCounter] = swappedInput[swapCounter].split("#")[0];
swappedInput[swapCounter] = swappedInput[swapCounter].split("#")[1];
usedIndex[useCounter] = useCounter;
}
for (int outputCounter = 0; outputCounter < input.length; outputCounter++) {
finalText = finalText + swappedInput[outputCounter] + " ";
}
println("The swapped inputs are: " + finalText + ".");
}
}
Because of randomality some times useCounter is the same as swapCounter and now look at those lines (assume useCounter and swapCounter are the same)
swappedInput[swapCounter] = input[swapCounter].concat("#" + input[useCounter]);
swappedInput[useCounter] = swappedInput[swapCounter].split("#")[0];
swappedInput[swapCounter] = swappedInput[swapCounter].split("#")[1];
In the second line you are changing the value of xxx#www to be www so in the third line when doing split you dont get an array with two values you get an empty result thats why exception is thrown in addition you should not use swappedInput because it beats the pourpuse (if i understand correctly yoush shoud not use temp values while you are using addition array which is worse) the correct sollution is to only use input array here is the solution
public class myFile {
public static boolean contains(int[] array, int key) {
Arrays.sort(array);
return Arrays.binarySearch(array, key) >= 0;
}
public static void println(Object line) {
System.out.println(line);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String finalText = "";
String[] input = new String[5];
int[] usedIndex = new int[input.length];
int swapCounter = input.length, useCounter;
for (int inputCounter = 0; inputCounter < input.length; inputCounter++) { //input
println("Enter input 1 " + (inputCounter + 1) + ": ");
input[inputCounter] = in.nextLine();
}
while (--swapCounter >= 0) {
do {
useCounter = (int) Math.floor(Math.random() * input.length);
}
while (contains(usedIndex, useCounter));
// Skip if results are the same
if (useCounter == swapCounter) {
swapCounter++;
continue;
}
input[swapCounter] = input[swapCounter].concat("#" + input[useCounter]);
input[useCounter] = input[swapCounter].split("#")[0];
input[swapCounter] = input[swapCounter].split("#")[1];
usedIndex[useCounter] = useCounter;
}
for (int outputCounter = 0; outputCounter < input.length; outputCounter++) {
finalText = finalText + input[outputCounter] + " ";
}
println("The swapped inputs are: " + finalText + ".");
}
}

Same word occurrence in a string. Java [duplicate]

I am writing a very basic java program that calculates frequency of each word in a sentence so far i managed to do this much
import java.io.*;
class Linked {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter the sentence");
String st = br.readLine();
st = st + " ";
int a = lengthx(st);
String arr[] = new String[a];
int p = 0;
int c = 0;
for (int j = 0; j < st.length(); j++) {
if (st.charAt(j) == ' ') {
arr[p++] = st.substring(c,j);
c = j + 1;
}
}
}
static int lengthx(String a) {
int p = 0;
for (int j = 0; j < a.length(); j++) {
if (a.charAt(j) == ' ') {
p++;
}
}
return p;
}
}
I have extracted each string and stored it in a array , now problem is actually how to count the no of instances where each 'word' is repeated and how to display so that repeated words not get displayed multiple times , can you help me in this one ?
Use a map with word as a key and count as value, somthing like this
Map<String, Integer> map = new HashMap<>();
for (String w : words) {
Integer n = map.get(w);
n = (n == null) ? 1 : ++n;
map.put(w, n);
}
if you are not allowed to use java.util then you can sort arr using some sorting algoritm and do this
String[] words = new String[arr.length];
int[] counts = new int[arr.length];
words[0] = words[0];
counts[0] = 1;
for (int i = 1, j = 0; i < arr.length; i++) {
if (words[j].equals(arr[i])) {
counts[j]++;
} else {
j++;
words[j] = arr[i];
counts[j] = 1;
}
}
An interesting solution with ConcurrentHashMap since Java 8
ConcurrentMap<String, Integer> m = new ConcurrentHashMap<>();
m.compute("x", (k, v) -> v == null ? 1 : v + 1);
In Java 8, you can write this in two simple lines! In addition you can take advantage of parallel computing.
Here's the most beautiful way to do this:
Stream<String> stream = Stream.of(text.toLowerCase().split("\\W+")).parallel();
Map<String, Long> wordFreq = stream
.collect(Collectors.groupingBy(String::toString,Collectors.counting()));
import java.util.*;
public class WordCounter {
public static void main(String[] args) {
String s = "this is a this is this a this yes this is a this what it may be i do not care about this";
String a[] = s.split(" ");
Map<String, Integer> words = new HashMap<>();
for (String str : a) {
if (words.containsKey(str)) {
words.put(str, 1 + words.get(str));
} else {
words.put(str, 1);
}
}
System.out.println(words);
}
}
Output:
{a=3, be=1, may=1, yes=1, this=7, about=1, i=1, is=3, it=1, do=1, not=1, what=1, care=1}
Try this
public class Main
{
public static void main(String[] args)
{
String text = "the quick brown fox jumps fox fox over the lazy dog brown";
String[] keys = text.split(" ");
String[] uniqueKeys;
int count = 0;
System.out.println(text);
uniqueKeys = getUniqueKeys(keys);
for(String key: uniqueKeys)
{
if(null == key)
{
break;
}
for(String s : keys)
{
if(key.equals(s))
{
count++;
}
}
System.out.println("Count of ["+key+"] is : "+count);
count=0;
}
}
private static String[] getUniqueKeys(String[] keys)
{
String[] uniqueKeys = new String[keys.length];
uniqueKeys[0] = keys[0];
int uniqueKeyIndex = 1;
boolean keyAlreadyExists = false;
for(int i=1; i<keys.length ; i++)
{
for(int j=0; j<=uniqueKeyIndex; j++)
{
if(keys[i].equals(uniqueKeys[j]))
{
keyAlreadyExists = true;
}
}
if(!keyAlreadyExists)
{
uniqueKeys[uniqueKeyIndex] = keys[i];
uniqueKeyIndex++;
}
keyAlreadyExists = false;
}
return uniqueKeys;
}
}
Output:
the quick brown fox jumps fox fox over the lazy dog brown
Count of [the] is : 2
Count of [quick] is : 1
Count of [brown] is : 2
Count of [fox] is : 3
Count of [jumps] is : 1
Count of [over] is : 1
Count of [lazy] is : 1
Count of [dog] is : 1
From Java 10 you can use the following:
import java.util.Arrays;
import java.util.stream.Collectors;
public class StringFrequencyMap {
public static void main(String... args){
String[] wordArray = {"One", "One", "Two","Three", "Two", "two"};
var freq = Arrays.stream(wordArray)
.collect(Collectors.groupingBy(x -> x, Collectors.counting()));
System.out.println(freq);
}
}
Output:
{One=2, two=1, Two=2, Three=1}
You could try this
public static void frequency(String s) {
String trimmed = s.trim().replaceAll(" +", " ");
String[] a = trimmed.split(" ");
ArrayList<Integer> p = new ArrayList<>();
for (int i = 0; i < a.length; i++) {
if (p.contains(i)) {
continue;
}
int d = 1;
for (int j = i+1; j < a.length; j++) {
if (a[i].equals(a[j])) {
d += 1;
p.add(j);
}
}
System.out.println("Count of "+a[i]+" is:"+d);
}
}
package naresh.java;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class StringWordDuplicates {
static void duplicate(String inputString){
HashMap<String, Integer> wordCount = new HashMap<String,Integer>();
String[] words = inputString.split(" ");
for(String word : words){
if(wordCount.containsKey(word)){
wordCount.put(word, wordCount.get(word)+1);
}
else{
wordCount.put(word, 1);
}
}
//Extracting of all keys of word count
Set<String> wordsInString = wordCount.keySet();
for(String word : wordsInString){
if(wordCount.get(word)>1){
System.out.println(word+":"+wordCount.get(word));
}
}
}
public static void main(String args[]){
duplicate("I am Java Programmer and IT Server Programmer with Java as Best Java lover");
}
}
class find
{
public static void main(String nm,String w)
{
int l,i;
int c=0;
l=nm.length();String b="";
for(i=0;i<l;i++)
{
char d=nm.charAt(i);
if(d!=' ')
{
b=b+d;
}
if(d==' ')
{
if(b.compareTo(w)==0)
{
c++;
}
b="";
}
}
System.out.println(c);
}
}
public class wordFrequency {
private static Scanner scn;
public static void countwords(String sent) {
sent = sent.toLowerCase().replaceAll("[^a-z ]", "");
ArrayList<String> arr = new ArrayList<String>();
String[] sentarr = sent.split(" ");
Map<String, Integer> a = new HashMap<String, Integer>();
for (String word : sentarr) {
arr.add(word);
}
for (String word : arr) {
int count = Collections.frequency(arr, word);
a.put(word, count);
}
for (String key : a.keySet()) {
System.out.println(key + " = " + a.get(key));
}
}
public static void main(String[] args) {
scn = new Scanner(System.in);
System.out.println("Enter sentence:");
String inp = scn.nextLine();
countwords(inp);
}
}
Determine the frequency of words in a file.
File f = new File(fileName);
Scanner s = new Scanner(f);
Map<String, Integer> counts =
new Map<String, Integer>();
while( s.hasNext() ){
String word = s.next();
if( !counts.containsKey( word ) )
counts.put( word, 1 );
else
counts.put( word,
counts.get(word) + 1 );
}
The following program finds the frequency, sorts it accordingly, and prints it.
Below is the output grouped by frequency:
0-10:
The 2
Is 4
11-20:
Have 13
Done 15
Here is my program:
package com.company;
import java.io.*;
import java.util.*;
import java.lang.*;
/**
* Created by ayush on 12/3/17.
*/
public class Linked {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter the sentence");
String st = br.readLine();
st=st.trim();
st = st + " ";
int count = lengthx(st);
System.out.println(count);
String arr[] = new String[count];
int p = 0;
int c = 0;
for (int i = 0; i < st.length(); i++) {
if (st.charAt(i) == ' ') {
arr[p] = st.substring(c,i);
System.out.println(arr[p]);
c = i + 1;
p++;
}
}
Map<String, Integer> map = new HashMap<>();
for (String w : arr) {
Integer n = map.get(w);
n = (n == null) ? 1 : ++n;
map.put(w, n);
}
for (String key : map.keySet()) {
System.out.println(key + " = " + map.get(key));
}
Set<Map.Entry<String, Integer>> entries = map.entrySet();
Comparator<Map.Entry<String, Integer>> valueComparator = new Comparator<Map.Entry<String,Integer>>() {
#Override
public int compare(Map.Entry<String, Integer> e1, Map.Entry<String, Integer> e2) {
Integer v1 = e1.getValue();
Integer v2 = e2.getValue();
return v1.compareTo(v2); }
};
List<Map.Entry<String, Integer>> listOfEntries = new ArrayList<Map.Entry<String, Integer>>(entries);
Collections.sort(listOfEntries, valueComparator);
LinkedHashMap<String, Integer> sortedByValue = new LinkedHashMap<String, Integer>(listOfEntries.size());
for(Map.Entry<String, Integer> entry : listOfEntries){
sortedByValue.put(entry.getKey(), entry.getValue());
}
for(Map.Entry<String, Integer> entry : listOfEntries){
sortedByValue.put(entry.getKey(), entry.getValue());
}
System.out.println("HashMap after sorting entries by values ");
Set<Map.Entry<String, Integer>> entrySetSortedByValue = sortedByValue.entrySet();
for(Map.Entry<String, Integer> mapping : entrySetSortedByValue){
System.out.println(mapping.getKey() + " ==> " + mapping.getValue());
}
}
static int lengthx(String a) {
int count = 0;
for (int j = 0; j < a.length(); j++) {
if (a.charAt(j) == ' ') {
count++;
}
}
return count;
}
}
import java.io.*;
class Linked {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter the sentence");
String st = br.readLine();
st = st + " ";
int a = lengthx(st);
String arr[] = new String[a];
int p = 0;
int c = 0;
for (int j = 0; j < st.length(); j++) {
if (st.charAt(j) == ' ') {
arr[p++] = st.substring(c,j);
c = j + 1;
}
}
}
static int lengthx(String a) {
int p = 0;
for (int j = 0; j < a.length(); j++) {
if (a.charAt(j) == ' ') {
p++;
}
}
return p;
}
}
Simply use Java 8 Stream collectors groupby function:
import java.util.function.Function;
import java.util.stream.Collectors;
static String[] COUNTRY_NAMES
= { "China", "Australia", "India", "USA", "USSR", "UK", "China",
"France", "Poland", "Austria", "India", "USA", "Egypt", "China" };
Map<String, Long> result = Stream.of(COUNTRY_NAMES).collect(
Collectors.groupingBy(Function.identity(), Collectors.counting()));
Count frequency of elements of list in java 8
List<Integer> list = new ArrayList<Integer>();
Collections.addAll(list,3,6,3,8,4,9,3,6,9,4,8,3,7,2);
Map<Integer, Long> frequencyMap = list.stream().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
System.out.println(frequencyMap);
Note :
For String frequency counting split the string and convert it to list and use streams for count frequency => (Map frequencyMap)*
Check below link
String s[]=st.split(" ");
String sf[]=new String[s.length];
int count[]=new int[s.length];
sf[0]=s[0];
int j=1;
count[0]=1;
for(int i=1;i<s.length;i++)
{
int t=j-1;
while(t>=0)
{
if(s[i].equals(sf[t]))
{
count[t]++;
break;
}
t--;
}
if(t<0)
{
sf[j]=s[i];
count[j]++;
j++;
}
}
Created a simple easy to understand solution for this problem covers all test cases-
import java.util.HashMap;
import java.util.Map;
/*
* Problem Statement - Count Frequency of each word in a given string, ignoring special characters and space
* Input 1 - "To be or Not to be"
* Output 1 - to(2 times), be(2 times), or(1 time), not(1 time)
*
* Input 2 -"Star 123 ### 123 star"
* Output - Star(2 times), 123(2 times)
*/
public class FrequencyofWords {
public static void main(String[] args) {
String s1="To be or not **** to be! is all i ask for";
fnFrequencyofWords(s1);
}
//-------Supporting Function-----------------
static void fnFrequencyofWords(String s1) {
//------- Convert String to proper format----
s1=s1.replaceAll("[^A-Za-z0-9\\s]","");
s1=s1.replaceAll(" +"," ");
s1=s1.toLowerCase();
//-------Create String to an array with words------
String[] s2=s1.split(" ");
System.out.println(s1);
//-------- Create a HashMap to store each word and its count--
Map <String , Integer> map=new HashMap<String, Integer>();
for(int i=0;i<s2.length;i++) {
if(map.containsKey(s2[i])) //---- Verify if Word Already Exits---
{
map.put(s2[i], 1+ map.get(s2[i])); //-- Increment value by 1 if word already exits--
}
else {
map.put(s2[i], 1); // --- Add Word to map and set value as 1 if it does not exist in map--
}
}
System.out.println(map); //--- Print the HashMap with Key, Value Pair-------
}
}
public class WordFrequencyProblem {
public static void main(String args[]){
String s="the quick brown fox jumps fox fox over the lazy dog brown";
String alreadyProcessedWords="";
boolean isCount=false;
String[] splitWord = s.split("\\s|\\.");
for(int i=0;i<splitWord.length;i++){
String word = splitWord[i];
int count = 0;
isCount=false;
if(!alreadyProcessedWords.contains(word)){
for(int j=0;j<splitWord.length;j++){
if(word.equals(splitWord[j])){
count++;
isCount = true;
alreadyProcessedWords=alreadyProcessedWords+word+" ";
}
}
}
if(isCount)
System.out.println(word +"Present "+ count);
}
}
}
public class TestSplit {
public static void main(String[] args) {
String input="Find the repeated word which is repeated in this string";
List<String> output= (List) Arrays.asList(input.split(" "));
for(String str: output) {
int occurrences = Collections.frequency(output, str);
System.out.println("Occurence of " + str+ " is "+occurrences);
}
System.out.println(output);
}
}
Please try these it may be help for you
public static void main(String[] args) {
String str1="I am indian , I am proud to be indian proud.";
Map<String,Integer> map=findFrquenciesInString(str1);
System.out.println(map);
}
private static Map<String,Integer> findFrquenciesInString(String str1) {
String[] strArr=str1.split(" ");
Map<String,Integer> map=new HashMap<>();
for(int i=0;i<strArr.length;i++) {
int count=1;
for(int j=i+1;j<strArr.length;j++) {
if(strArr[i].equals(strArr[j]) && strArr[i]!="-1") {
strArr[j]="-1";
count++;
}
}
if(count>1 && strArr[i]!="-1") {
map.put(strArr[i], count);
strArr[i]="-1";
}
}
return map;
}
try this
public void count()throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enetr the strring");
String s = in.readLine();
int l = s.length();
int a=0,b=0,c=0,i,j,y=0;
char d;
String x;
String n[] = new String [50];
int m[] = new int [50];
for (i=0;i<50;i++)
{
m[i]=0;
}
for (i=0;i<l;i++)
{
d = s.charAt(i);
if((d==' ')||(d=='.'))
{
x = s.substring(a,i);
a= i+1;
for(j=0;j<b;j++)
{
if(x.equalsIgnoreCase(n[j]) == true)
{
m[j]++;
c = 1;
}
}
if(c==0)
{
n[b] = x;
m[b] = 1;
b++;
}
}
c=0;
}
for(i=0;i<b;i++)
{
for (j=0;j<b;j++)
{
if(y<m[j])
{
y=m[j];
}
}
if(m[i]==y)
{
System.out.println(n[i] + " : " + m[i]);
m[i]=0;
}
y=0;
}
}

Array wont work with small sentences

If I change the text to two words the program wont output anything. Not a clue on how to fix this, thanks in advance.
public class test {
public static void main(String args[]) {
String text = "The cat sat on the mat!"; //Change the string to "Hello there!"
int wordLengthCount [] = new int [20];
String wordCountText = "";
String sentence[] = text.split("[,\\-:\\?\\!\\ ]");
for (int i = 0; i < sentence.length; i++)
{
wordLengthCount[sentence[i].length()]++;
}
for(int wordLength=0; wordLength<sentence.length; wordLength++)
{
if (wordLengthCount[wordLength] != 0){
wordCountText += wordLengthCount[wordLength] + " with length of " + wordLength + "\n";
}
}
System.out.println(wordCountText);
}
}
You need to iterate over all wordLengthCount
Quick fix:
for (int wordLength = 0; wordLength < wordLengthCount.length; wordLength++) {
if (wordLengthCount[wordLength] != 0) {
wordCountText += wordLengthCount[wordLength] + " with length of " + wordLength + "\n";
}
}
Live demo

Unable to display Tag

Okay I am following on another question i posted a week ago.
Unable to parse ^ character
My current situation is that now I am able to parse the required Regex and create subsequent elements. I have created tags for each element type .
For eg my input string is A|1|2|3^4|B||1|2|3^4^5
So my tags in this string are A and B
My Output shall be (expected)
A1 1
A2 2
A3.1 3
A3.2 4
B1 (BLANK) //not B
B2 1
B3 2
B4.1 3
B4.2 4
B4.3 5
The reason B1 should be blank because input is B||1|2.
My current output is coming to be
element1 A
element2 1
element3.1 2
element3.2 3
element4 4
element5 B
element6
element7.1 2
element7.2 3
element7.3 4
element7.4 5
Basically, I am trying to construct an HL7 parser. replacements with the accurate tags are done to avoid confusion and maintain confidentiality. The code is as below.
public class Parser {
public static final String ELEMENT_DELIM_REGEX = "\\|";
public static void main(String[] args) {
String input = "A|1|2|3^4|";
String[] tokens = input.split(ELEMENT_DELIM_REGEX);
Element[] elements = new Element[tokens.length];
for (int i = 0; i < tokens.length; i++) {
elements[i] = new Element(i + 1, tokens[i]);
}
for (Element element : elements) {
System.out.println(element);
}
}
}
and
Element.java
public class Element {
public static final String SUB_ELEMENT_DELIM_REGEX = "\\^";
private int number;
private String[] content;
public Element(int number, String content) {
this.number = number;
this.content = content.split(SUB_ELEMENT_DELIM_REGEX);
}
#Override
public String toString() {
if (content.length == 1) {
return "Element " + number + "\t" + content[0];
}
StringBuilder str = new StringBuilder();
for (int i = 0; i < content.length; i++) {
str.append("Element " + number + "." + (i+1) + "\t" + content[i] + "\n");
}
// Delete the last \n
str.replace(str.length() - 1, str.length(), "");
return str.toString();
} }
It can be achieved by a few little changes in the two classes: (Ask me if you don't understand what's happening in the code, I wrote only a few comments and but tried to keep it self-explaining)
public class Parser {
public static final String ELEMENT_DELIM_REGEX = "\\|";
public static void main(String[] args) {
String input = "A|1|2|3^4|B||1|2|3^4^5";
String[] tokens = input.split(ELEMENT_DELIM_REGEX);
List<Element> elements = new ArrayList<Element>();
String currentTag = "";
int elementCounter = 1;
for (int i = 0; i < tokens.length; i++) {
if (tokens[i].matches("\\p{Alpha}+")) {
currentTag = tokens[i];
elementCounter = 1;
continue;
}
elements.add(new Element(elementCounter++, currentTag, tokens[i]));
}
for (Element element : elements) {
System.out.println(element);
}
}
}
and
public class Element {
public static final String SUB_ELEMENT_DELIM_REGEX = "\\^";
private int number;
private String[] content;
private String tag;
public Element(int number, String tag, String content) {
this.number = number;
this.content = content.split(SUB_ELEMENT_DELIM_REGEX);
this.tag = tag;
}
#Override
public String toString() {
if (content.length == 1) {
return tag + "" + number + "\t" + content[0];
}
StringBuilder str = new StringBuilder();
for (int i = 0; i < content.length; i++) {
str.append(tag + "" + number + "." + (i+1) + "\t" + content[i] + "\n");
}
// Delete the last \n
str.replace(str.length() - 1, str.length(), "");
return str.toString();
}
}
Output (for your input A|1|2|3^4|B||1|2|3^4^5 )
A1 1
A2 2
A3.1 3
A3.2 4
B1
B2 1
B3 2
B4.1 3
B4.2 4
B4.3 5

Categories