Unable to display Tag - java

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

Related

How to swap every 2 letters in a String? - Java

So I'm currently working on a personal project and I made a program that tries to swap every 2 letter in a given string.
So I want the output like this:
(Note Input String is "abllte")
ballet
So I wrote this method
public static String codeString(String input) {
String firstLetter = "";
String secoundLetter = "";
String result = "";
for(int i = 0; i < input.length()-1; i++){
for(int c = 0; c < i; c = c +2)
{
firstLetter = input.substring(c,c + 1);
secoundLetter = input.substring(c + 1, c + 2);
}
result = result + secoundLetter + firstLetter;
}
return result;
}
But I get this output:
ababllll
Any idea how to solve this?
Thank you in advance!
You only need one loop. This works for both even and odd length character strings.
first, the methods used return the StringBuilder in its current modified state.
So sb.insert(i, sb.charAt(i+1)) inserts the char at i+1 at i
So if sb contained ab, StringBuilder would now contain bab
insert returns the modifed StringBuilder so now sb.deleteCharAt(i+2) deletes the second a (the one that was just copied).
this is then repeated until all characters are swapped.
Because of the constant inserting and deletion of characters this is not very efficient.
for (String s : new String[] { "abcdefg", "abcdefgh" }) {
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length() - 1; i += 2) {
sb.insert(i, sb.charAt(i + 1)).deleteCharAt(i + 2);
}
System.out.println(s + " -> " + sb);
}
Prints
abcdefg -> badcfeg
abcdefgh -> badcfehg
For a more efficient algorithm, this would be the way to go. It's also much more intuitive.
for (String s : new String[] { "abcdefg", "abcdefgh" }) {
char ch[] = s.toCharArray();
for (int i = 0; i < ch.length - 1; i+=2) {
char c = ch[i];
ch[i] = ch[i + 1];
ch[i + 1] = c;
}
String d = String.valueOf(ch);
System.out.println(s + " -> " + d);
}
This prints the same as above.
I'm not sure what the point of your nested for loop is. You can do this with just one loop.
public static String codeString(String input) {
String firstLetter = "";
String secoundLetter = "";
String result = "";
for(int i = 0; i < input.length()-1; i+=2){
firstLetter = input.substring(i,i+1);
secoundLetter = input.substring(i+1,i+2);
result = result + secoundLetter + firstLetter;
}
return result;
}
If your input string has an odd number of characters, you'll have to append the extra last character.
public static String codeString(String input) {
String firstLetter = "";
String secoundLetter = "";
String result = "";
for(int i = 0; i < input.length()-1; i+=2){
firstLetter = input.substring(i, i+1);
secoundLetter = input.substring(i+1, i+2);
result = result + secoundLetter + firstLetter;
}
if(input.length() % 2 == 1)
result += input.substring(input.length()-1, input.length());
return result;
}
You do not need a nested loop. Change the outer loop to step by 2 i.e. i = i + 2 and remove the inner loop.
public class Main {
public static void main(String[] args) {
System.out.println(codeString("abllte"));
}
public static String codeString(String input) {
String firstLetter = "";
String secondLetter = "";
String result = "";
for (int i = 0; i < input.length() - 1; i = i + 2) {
firstLetter = input.substring(i, i + 1);
secondLetter = input.substring(i + 1, i + 2);
result = result + secondLetter + firstLetter;
}
return result;
}
}
Output:
ballet
An alternative approach:
You can create a function with two parameters: input string as the first parameter and n as the second parameter, where every n characters in the input string need to be reversed.
public class Main {
public static void main(String[] args) {
System.out.println(codeString("abllte", 1));
System.out.println(codeString("abllte", 2));
System.out.println(codeString("abllte", 3));
System.out.println(codeString("abllte", 4));
}
public static String codeString(String input, int n) {
if (n <= input.length() / 2) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < input.length() - n + 1; i = i + n) {
result.append(new StringBuilder(input.substring(i, i + n)).reverse());
}
return result.toString();
} else {
return input;
}
}
}
Output:
abllte
ballet
lbaetl
abllte

Append string after nth occurrence of a string

I have a string s to which I want to append another string s1 at the specified position.
String s = "17.4755,2.0585,23.6489,12.0045";
String s1=",,,,"
Now I want to add the string s1 after the n-th occurrence of "," character.
I have just started learning Java.
You can use the following method:
public String insert(int n, String original, String other) {
int index = original.indexOf(',');
while(--n > 0 && index != -1) {
index = original.indexOf(',', index + 1);
}
if(index == -1) {
return original;
} else {
return original.substring(0, index) + other + original.substring(index);
}
}
Working with Strings directly is not worth the trouble.
One easy way would be to turn your String into a List and manipulate that.
public void test() {
String s = "17.4755,2.0585,23.6489,12.0045";
// Split s into parts.
String[] parts = s.split(",");
// Convert it to a list so we can insert.
List<String> list = new ArrayList<>(Arrays.asList(parts));
// Inset 3 blank fields at position 2.
for (int i = 0; i < 3; i++) {
list.add(2,"");
}
// Create my new string.
String changed = list.stream().collect(Collectors.joining(","));
System.out.println(changed);
}
Prints:
17.4755,2.0585,,,,23.6489,12.0045
I think this is what you want
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = "17.4755,2.0585,23.6489,12.0045";
String s1=",,,,";
System.out.println("Enter Nth Occurrence");
try {
int n = scanner.nextInt();
long totalOccurrence = 0;
if (n != 0) {
totalOccurrence = s.chars().filter(num -> num == ',').count();
if (totalOccurrence < n) {
System.out.println("String s have only " + totalOccurrence + " symbol \",\"");
} else {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ',') {
count++;
if (count == n) {
String resultString = s.substring(0, i) + s1 + s.substring(i, s.length());
System.out.println(resultString);
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Wrong input");
}
}
}
Output :
1. Enter Nth Occurrence
5
String s have only 3 symbol ","
2. Enter Nth Occurrence
2
17.4755,2.0585,,,,,23.6489,12.0045

How to parse and compare text?

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);
}}

Single character instance from string

i was wondering how can i create a method where i can get the single instance from a string and give it a numericValue for example, if theres a String a = "Hello what the hell" there are 4 l characters and i want to give a substring from the String a which is Hello and give it numeric values. Right now in my program it gets all the character instances from string so the substring hello would get number values from the substring hell too because it also has the same characters.
my code :
public class Puzzle {
private static char[] letters = {'a','b','c','d','e','f','g','h','i', 'j','k','l','m','n','o','p','q','r','s',
't','u','v','w','x','y','z'};
private static String input;
private static String delimiters = "\\s+|\\+|//+|=";
public static void main(String[]args)
{
input = "help + me = please";
System.out.println(putValues(input));
}
//method to put numeric values for substring from input
#SuppressWarnings("static-access")
public static long putValues(String input)
{
Integer count;
long answer = 0;
String first="";
String second = "";
StringBuffer sb = new StringBuffer(input);
int wordCounter = Countwords();
String[] words = countLetters();
System.out.println(input);
if(input.isEmpty())
{
System.out.println("Sisestage mingi s6na");
}
if(wordCounter == -1 ||countLetters().length < 1){
return -1;
}
for(Character s : input.toCharArray())
{
for(Character c : letters)
{
if(s.equals(c))
{
count = c.getNumericValue(c) - 9;
System.out.print(s.toUpperCase(s) +"="+ count + ", ");
}
}
if(words[0].contains(s.toString()))
{
count = s.getNumericValue(s);
//System.out.println(count);
first += count.toString();
}
if(words[3].contains(s.toString())){
count = s.getNumericValue(s);
second += count.toString();
}
}
try {
answer = Long.parseLong(first)+ Long.parseLong(second);
} catch(NumberFormatException ex)
{
System.out.println(ex);
}
System.out.println("\n" + first + " + " + second + " = " + answer);
return answer;
}
public static int Countwords()
{
String[] countWords = input.split(" ");
int counter = countWords.length - 2;
if(counter == 0) {
System.out.println("Sisend puudu!");
return -1;
}
if(counter > 1 && counter < 3) {
System.out.println("3 sõna peab olema");
return -1;
}
if(counter > 3) {
System.out.println("3 sõna max!");
return -1;
}
return counter;
}
//method which splits input String and returns it as an Array so i can put numeric values after in the
//putValue method
public static String[] countLetters()
{
int counter = 0;
String[] words = input.split(delimiters);
for(int i = 0; i < words.length;i++) {
counter = words[i].length();
if(words[i].length() > 18) {
System.out.println("One word can only be less than 18 chars");
}
}
return words;
}
Program has to solve the word puzzles where you have to guess which digit corresponds to which letter to make a given equality valid. Each letter must correspond to a different decimal digit, and leading zeros are not allowed in the numbers.
For example, the puzzle SEND+MORE=MONEY has exactly one solution: S=9, E=5, N=6, D=7, M=1, O=0, R=8, Y=2, giving 9567+1085=10652.
import java.util.ArrayList;
public class main {
private static String ChangeString;
private static String[] ArrayA;
private static String a;
private static int wordnumber;
private static String temp;
public static void main(String[] args) {
// TODO Auto-generated method stub
a = "hello what the hell";
wordnumber = 0;
identifyint(a,wordnumber);
}
public static void identifyint (String a, int WhichWord){
ChangeString = a.split(" ")[WhichWord];
ArrayA = a.split(" ");
replaceword();
ArrayA[wordnumber] = ChangeString;
//System.out.print(ArrayA[wordnumber]);
a = "";
for(int i = 0; i<ArrayA.length;i++){
if(i==wordnumber){
a = a.concat(temp+ " ");
}
else{
a = a.concat(ArrayA[i]+" ");
}
}
System.out.print(a);
}
public static void replaceword(){
temp = "";
Character arr[] = new Character[ChangeString.length()];
for(int i = 0; i<ChangeString.length();i++){
arr[i] = ChangeString.charAt(i);
Integer k = arr[i].getNumericValue(arr[i])-9;
temp = temp.concat(""+k);
}
a = temp;
}
}
Change wordnumber to the word you want to replace each time. If this is not what you have asked for, please explain your question in more detail.

Count variable not working

I am writing a program to take in a tweet as input and return a value of the unique hashtags used in the tweet. However in the countUniqueHashtags method, my hashtagCount variable will only return a value of 1 if the input contains hashtags(even if there is more than one) and a value of 0 if the input doesn't contain any hashtags.
public class UniqueHashtagCounter
{
static ArrayList<String> uniqueHashTags = new ArrayList<String>();
int numberOfTweetsToFollow;
public String tweetSpace = "";
Scanner in = new Scanner(System.in);
public int getTweetsToFollow()
{
System.out.println("Enter the number of Tweets you wish to follow: ");
numberOfTweetsToFollow = in.nextInt();
return numberOfTweetsToFollow;
}
public String tweetsInput()
{
for(int i = 0; i <= numberOfTweetsToFollow ; ++i)
{
if(in.hasNextLine()){
tweetSpace = tweetSpace + in.nextLine();
}
}
return tweetSpace;
}
public ArrayList<String> populateArray()
{
uniqueHashTags.add(tweetSpace);
for(String s: uniqueHashTags)
s.toLowerCase().split(" ");
for(int x = 0; x < uniqueHashTags.size(); x++){
countUniqueHashtags(uniqueHashTags);}
return uniqueHashTags;
}
static void countUniqueHashtags(ArrayList<String> strings)
{
int hashtagCount = uniqueHashTags.size();
ListIterator<String> listIterator = strings.listIterator();
while(listIterator.hasNext())
{
String e = listIterator.next();
if(e.startsWith("#"))
hashtagCount = hashtagCount + 1;
}
System.out.println("The number of unique hashtags is: " + hashtagCount);
}
"My hashtagCount variable will only return a value of 1 if the input contains hashtags(even if there is more than one) and a value of 0 if the input doesn't contain any hashtags"
That's because you are using startsWith():
if(e.startsWith("#"))
hashtagCount = hashtagCount + 1;
You need to loop through the string and count the hashtag characters:
for(int i=0; e.length();i++){
if(e.charAt(i)=='#') hashtagcount++;
}

Categories