Replace strings in a long String: - java

I have the following string:
Where Are You [Employee Name]?
your have a [Shift] shift...
and a list of strings that contains:
1. Employee Name
2. Shift
I need to find the given strings in the list in the long string and replace them with another content (including the [ and ] characters).
So for example the first string is need to be change to:
Where Are You Jhon Green?
your have a morning shift...
Is there any simple way to do that? using IndexOf will give me the location of this string but how would I include the [ , ] charecters as well?
UPDATE:
This is the code I tested so far:
Scanner sc = new Scanner(smsText);
for (String s; (s = sc.findWithinHorizon("(?<=\\[).*?(?=\\])", 0)) != null;)
{
words.add(s);
}
for (int j = 0; j < words.size(); j++)
{
Log.d(TAG, "The value for column: "+words.get(j) +" is: "+ rowData.getValue(words.get(j)));
smsText.replaceFirst("\\[" + words.get(j) + "\\]", rowData.getValue(words.get(j)));
}
Log.d(TAG, "Final String is: "+ smsText);
which is not giving me the right result, the string are not replaced.
UPDATE2:
The solution that worked for me is:
Scanner sc = new Scanner(smsText);
for (String s; (s = sc.findWithinHorizon("(?<=\\[).*?(?=\\])", 0)) != null;)
{
columnNames.add(s);
}
for (int j = 0; j < columnNames.size(); j++)
{
Log.d(TAG, "The value for column: "+columnNames.get(j) +" is: "+ rowData.getValue(columnNames.get(j)));
smsText = smsText.replaceFirst("\\[" + columnNames.get(j) + "\\]", rowData.getValue(columnNames.get(j)));
}
Log.d(TAG, "Final String is: "+ smsText);
Thanks to all for your help.

String key = myColumns.getName();
s.replaceFirst("\\[" + key + "\\]", myReplacements.getReplacement(key));
You could also use indexOf, but with a replace function it's immediately clear what you're trying to do.

try this
String s = "Where Are You [Employee Name]? your have a [Shift] shift..";
Map<String, String> replacementMap = new HashMap<>();
replacementMap.put("[Employee Name]", "John Green");
replacementMap.put("[Shift]", "morning");
for(Entry<String, String> e : replacementMap.entrySet()) {
s = s.replace(e.getKey(), e.getValue());
}
System.out.println(s);
output
Where Are You John Green? your have a morning shift..

A general solution could look something like this:
String message = "Where are you [Employee Name]? You have a [Shift] shift!";
Map<String, String> variables = new HashMap<>();
variables.put("Employee Name", "John Green");
variables.put("Shift", "morning");
StringBuffer endResult = new StringBuffer();
Matcher m = Pattern.compile("\\[(.*?)\\]").matcher(message);
while (m.find()) {
m.appendReplacement(endResult, variables.get(m.group(1)));
}
m.appendTail(endResult);
System.out.println(endResult.toString());

i know regex is there but if you want to go for recursive function here it is
public string replaceString(string str, string[] values, int index)
{
if (str.IndexOf('[') == -1 || str.IndexOf(']') == -1 || index > values.Length-1)
return str;
else
return replaceString(str.Replace(str.Substring(str.IndexOf('['), (str.IndexOf(']') - str.IndexOf('['))+1), values[index]), values, ++index);
}
calling this method
string strforreplac = "Where Are You [Employee Name]? your have a [Shift] shift...]";
string[] strvalues = {"Emil","morning"};
string newstring = replaceString(strforreplac,strvalues,0);

Related

Reverse a sentence using StringBuilder

The below code I used string as result and just reverse sentence for example input: " the sky is blue " and I get output:"blue is sky the". How I can use SpringBuilder instead String and then how I can reverse sentence and also words? example input: " the sky is blue " and I want this output "eulb is yks eht"
Please help me to modify the below code.
public String reverseWords(String s) {
int i = 0;
int j = 0;
String result = "";
while(s.length()>i){
while(s.length()>i && s.charAt(i)==' '){
i++;
}
if(i>=s.length()) break;
j = i;
while(s.length()>j && s.charAt(j)!=' '){
j++;
}
String word = s.substring(i,j);
result = word+" "+result;
i = j;
}
return result.trim();
}
You can use StringBuilder as follows:
String str = " the sky is blue ";
str = str.replaceAll("\\s+", " ");
StringBuilder sb = new StringBuilder(str.trim());
System.out.println(sb.reverse().toString());
Output:
eulb si yks eht

Map some names and values using java

I have a set of values as a repsonse like this.
from this
4,0,1581664239228,6,799,0,845,253,0,0,0,0,0,0,0,0,0,0,1448,594,0,1276257,0,0,0,0,1100,0,0,0,0,0,0,0,2047,2158,0,13,1
I have to map these values to below one..The order should be same like version: 4 , build: 0, tuneStartBaseUTCMS: 1581664239228 etc etc
version,build,tuneStartBaseUTCMS,ManifestDLStartTime,ManifestDLTotalTime,ManifestDLFailCount,VideoPlaylistDLStartTime,VideoPlaylistDLTotalTime,VideoPlaylistDLFailCount,AudioPlaylistDLStartTime,AudioPlaylistDLTotalTime,AudioPlaylistDLFailCount,VideoInitDLStartTime,VideoInitDLTotalTime,VideoInitDLFailCount,AudioInitDLStartTime,AudioInitDLTotalTime,AudioInitDLFailCount,VideoFragmentDLStartTime,VideoFragmentDLTotalTime,VideoFragmentDLFailCount,VideoBitRate,AudioFragmentDLStartTime,AudioFragmentDLTotalTime,AudioFragmentDLFailCount,AudioBitRate,drmLicenseAcqStartTime,drmLicenseAcqTotalTime,drmFailErrorCode,LicenseAcqPreProcessingDuration,LicenseAcqNetworkDuration,LicenseAcqPostProcDuration,VideoFragmentDecryptDuration,AudioFragmentDecryptDuration,gstPlayStartTime,gstFirstFrameTime,contentType,streamType,firstTune
I have written as follows...but it is not working as ex
String abcd = "4,0,1581664239228,6,799,0,845,253,0,0,0,0,0,0,0,0,0,0,1448,594,0,1276257,0,0,0,0,1100,0,0,0,0,0,0,0,2047,2158,0,13,1";
String valueName = "version,build,tuneStartBaseUTCMS,ManifestDLStartTime,ManifestDLTotalTime,ManifestDLFailCount,VideoPlaylistDLStartTime,VideoPlaylistDLTotalTime,VideoPlaylistDLFailCount,AudioPlaylistDLStartTime,AudioPlaylistDLTotalTime,AudioPlaylistDLFailCount,VideoInitDLStartTime,VideoInitDLTotalTime,VideoInitDLFailCount,AudioInitDLStartTime,AudioInitDLTotalTime,AudioInitDLFailCount,VideoFragmentDLStartTime,VideoFragmentDLTotalTime,VideoFragmentDLFailCount,VideoBitRate,AudioFragmentDLStartTime,AudioFragmentDLTotalTime,AudioFragmentDLFailCount,AudioBitRate,drmLicenseAcqStartTime,drmLicenseAcqTotalTime,drmFailErrorCode,LicenseAcqPreProcessingDuration,LicenseAcqNetworkDuration,LicenseAcqPostProcDuration,VideoFragmentDecryptDuration,AudioFragmentDecryptDuration,gstPlayStartTime,gstFirstFrameTime,contentType,streamType,firstTune";
String[] valueArr = abcd.split(",");
String[] valueNameArr = valueName.split(",");
List<String> valueList = Arrays.asList(valueArr);
List<String> valueNameList = Arrays.asList(valueNameArr);
System.out.println(valueList.size() + "jjj: " + "valueNameList::: " + valueNameList.size());
LinkedHashMap<String, String> result = new LinkedHashMap<String, String>();
for (String name : valueNameList) {
System.out.println("name: " + name);
for (String value : valueList) {
System.out.println("value: " + value);
result.put(name, value);
}
}
System.out.println("RESULT::::::::::::::::::::::::::::" + result);
Result prints:
{version=1, build=1, tuneStartBaseUTCMS=1, ManifestDLStartTime=1, ManifestDLTotalTime=1, ManifestDLFailCount=1, VideoPlaylistDLStartTime=1, VideoPlaylistDLTotalTime=1, VideoPlaylistDLFailCount=1, AudioPlaylistDLStartTime=1, AudioPlaylistDLTotalTime=1, AudioPlaylistDLFailCount=1, VideoInitDLStartTime=1, VideoInitDLTotalTime=1, VideoInitDLFailCount=1, AudioInitDLStartTime=1, AudioInitDLTotalTime=1, AudioInitDLFailCount=1, VideoFragmentDLStartTime=1, VideoFragmentDLTotalTime=1, VideoFragmentDLFailCount=1, VideoBitRate=1, AudioFragmentDLStartTime=1, AudioFragmentDLTotalTime=1, AudioFragmentDLFailCount=1, AudioBitRate=1, drmLicenseAcqStartTime=1, drmLicenseAcqTotalTime=1, drmFailErrorCode=1, LicenseAcqPreProcessingDuration=1, LicenseAcqNetworkDuration=1, LicenseAcqPostProcDuration=1, VideoFragmentDecryptDuration=1, AudioFragmentDecryptDuration=1, gstPlayStartTime=1, gstFirstFrameTime=1, contentType=1, streamType=1, firstTune=1}
Your loop is wrong
Try this
for(int i = 0; i < valueList.size(); i++){
result.put(valueNameList(i), valueList(i));
}
Is there not supposed to be a one-to-one relationship between abcd values and valueName ? If there is one-to-one, then an inner loop is wrong isn't it.
String abcd = "4,0,1581664239228,6,799,0,845,253,0,0,0,0,0,0,0,0,0,0,1448,594,0,1276257,0,0,0,0,1100,0,0,0,0,0,0,0,2047,2158,0,13,1";
String valueName = "version,build,tuneStartBaseUTCMS,ManifestDLStartTime,ManifestDLTotalTime,ManifestDLFailCount,VideoPlaylistDLStartTime,VideoPlaylistDLTotalTime,VideoPlaylistDLFailCount,AudioPlaylistDLStartTime,AudioPlaylistDLTotalTime,AudioPlaylistDLFailCount,VideoInitDLStartTime,VideoInitDLTotalTime,VideoInitDLFailCount,AudioInitDLStartTime,AudioInitDLTotalTime,AudioInitDLFailCount,VideoFragmentDLStartTime,VideoFragmentDLTotalTime,VideoFragmentDLFailCount,VideoBitRate,AudioFragmentDLStartTime,AudioFragmentDLTotalTime,AudioFragmentDLFailCount,AudioBitRate,drmLicenseAcqStartTime,drmLicenseAcqTotalTime,drmFailErrorCode,LicenseAcqPreProcessingDuration,LicenseAcqNetworkDuration,LicenseAcqPostProcDuration,VideoFragmentDecryptDuration,AudioFragmentDecryptDuration,gstPlayStartTime,gstFirstFrameTime,contentType,streamType,firstTune";
String[] list1 = abcd.split(",");
String[] list2 = valueName.split(",");
if (list1.length == list2.length) {
for (int x = 0; x < list1.length; x++) {
System.out.println(list2[x] + ":" + list1[x]);
}
}
Simply split and iterate
result
version:4
build:0
tuneStartBaseUTCMS:1581664239228
ManifestDLStartTime:6
ManifestDLTotalTime:799
ManifestDLFailCount:0
VideoPlaylistDLStartTime:845
VideoPlaylistDLTotalTime:253
VideoPlaylistDLFailCount:0
AudioPlaylistDLStartTime:0
AudioPlaylistDLTotalTime:0
AudioPlaylistDLFailCount:0
VideoInitDLStartTime:0
VideoInitDLTotalTime:0
VideoInitDLFailCount:0
AudioInitDLStartTime:0
AudioInitDLTotalTime:0
AudioInitDLFailCount:0
VideoFragmentDLStartTime:1448
VideoFragmentDLTotalTime:594
VideoFragmentDLFailCount:0
VideoBitRate:1276257
AudioFragmentDLStartTime:0
AudioFragmentDLTotalTime:0
AudioFragmentDLFailCount:0
AudioBitRate:0
drmLicenseAcqStartTime:1100
drmLicenseAcqTotalTime:0
drmFailErrorCode:0
LicenseAcqPreProcessingDuration:0
LicenseAcqNetworkDuration:0
LicenseAcqPostProcDuration:0
VideoFragmentDecryptDuration:0
AudioFragmentDecryptDuration:0
gstPlayStartTime:2047
gstFirstFrameTime:2158
contentType:0
streamType:13
firstTune:1

Find the most common word from user input

I'm very new to Java creating a software application that allows a user to input text into a field and the program runs through all of the text and identifies what the most common word is. At the moment, my code looks like this:
JButton btnMostFrequentWord = new JButton("Most Frequent Word");
btnMostFrequentWord.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text = textArea.getText();
String[] words = text.split("\\s+");
HashMap<String, Integer> occurrences = new HashMap<String, Integer>();
for (String word : words) {
int value = 0;
if (occurrences.containsKey(word)) {
value = occurrences.get(word);
}
occurrences.put(word, value + 1);
}
JOptionPane.showMessageDialog(null, "Most Frequent Word: " + occurrences.values());
}
}
This just prints what the values of the words are, but I would like it to tell me what the number one most common word is instead. Any help would be really appreciated.
Just after your for loop, you can sort the map by value then reverse the sorted entries by value and select the first.
for (String word: words) {
int value = 0;
if (occurrences.containsKey(word)) {
value = occurrences.get(word);
}
occurrences.put(word, value + 1);
}
Map.Entry<String,Integer> tempResult = occurrences.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.findFirst().get();
JOptionPane.showMessageDialog(null, "Most Frequent Word: " + tempResult.getKey());
For anyone who is more familiar with Java, here is a very easy way to do it with Java 8:
List<String> words = Arrays.asList(text.split("\\s+"));
Collections.sort(words, Comparator.comparingInt(word -> {
return Collections.frequency(words, word);
}).reversed());
The most common word is stored in words.get(0) after sorting.
I would do something like this
int max = 0;
String a = null;
for (String word : words) {
int value = 0;
if(occurrences.containsKey(word)){
value = occurrences.get(word);
}
occurrences.put(word, value + 1);
if(max < value+1){
max = value+1;
a = word;
}
}
System.out.println(a);
You could sort it, and the solution would be much shorter, but I think this runs faster.
You can either iterate through occurrences map and find the max or
Try like below
String text = textArea.getText();;
String[] words = text.split("\\s+");
HashMap<String, Integer> occurrences = new HashMap<>();
int mostFreq = -1;
String mostFreqWord = null;
for (String word : words) {
int value = 0;
if (occurrences.containsKey(word)) {
value = occurrences.get(word);
}
value = value + 1;
occurrences.put(word, value);
if (value > mostFreq) {
mostFreq = value;
mostFreqWord = word;
}
}
JOptionPane.showMessageDialog(null, "Most Frequent Word: " + mostFreqWord);

Delete element last occurrence in array

If a row of an array had the characters:
line = "I appreciate you helping me out!"
Let's say I wanted to delete the last occurrence of the letter 'e'.
How?
i.e. the result should be:
"I appreciate you helping m out!"
Here is my idea and I know the syntax is wrong. I start at 26 because that's the last time position an 'e' happens in the length of the string.
for (int i = 26; i < line.length() ; i++)
line.chars('e') = (line.chars('') && line.chars(i));
}
String line = "I appreciate you helping me out!";
int index = line.lastIndexOf('e');
if(index != -1) //prevent IndexOutOfBoundsException in case it can't find the char
line = new StringBuilder(line).deleteCharAt(index).toString();
or
String line = "I appreciate you helping me out!";
for (int i = line.length(); --i >= 0;){
if(line.charAt(i) == 'e'){
line = line.substring(0, i) + line.substring(i + 1);
break;
}
}
Or you can use regular expression like below :
String word = "I appreciate you helping me out!";
System.out.println(word.replaceAll("[e]([^e]*)$","$1"));
Out-put :
I appreciate you helping m out!
please try the below code snippet. Ideally it should work in generic way.
StringBuilder line = new StringBuilder(
"I appreciate you helping me out!");
System.out.println("Given input String :" + line);
int lastOccuranceIndex = 0;
int deleteIndex = 0;
char[] charr = line.toString().toLowerCase().toCharArray();
Map<Character, List<Integer>> charMap = new LinkedHashMap<Character, List<Integer>>();
List<Integer> indexList = null;
for (int i = 0; i < charr.length; i++) {
if (charMap.containsKey(charr[i])) {
indexList = charMap.get(charr[i]);
indexList.add(i);
charMap.put(charr[i], indexList);
} else if (Character.isAlphabetic(charr[i])) {
indexList = new ArrayList<Integer>();
indexList.add(i);
charMap.put(charr[i], indexList);
}
}
for (Entry<Character, List<Integer>> entry : charMap.entrySet()) {
indexList = entry.getValue();
if (indexList.size() > 2) {
// System.out.println(entry.getKey()
// +" last but one : "+indexList.get(indexList.size() -2));
if (indexList.get(indexList.size() - 2) > lastOccuranceIndex) {
lastOccuranceIndex = indexList.get(indexList.size() - 2);
deleteIndex = indexList.get(indexList.size() - 1);
}
}
}
System.out.println("last occurance character index "
+ lastOccuranceIndex + " and the character to delete is :"
+ charr[lastOccuranceIndex]);
char deleteChar = line.charAt(deleteIndex);
System.out.println("deleteChar :" + deleteChar + " at index :"
+ deleteIndex);
line = line.deleteCharAt(deleteIndex);
System.out.println("String content after delete operation : " + line);
output:
Given input String :I appreciate you helping me out!
last occurance character index 18 and the character to delete is :e
deleteChar :e at index :26
String content after delete operation : I appreciate you helping m out!
Regex to the rescue:
line = line.replaceAll("e(?=[^e]*$)", "");
The regex (?=[^e]*$) is a look ahead the requires there to be no occurrences of e anywhere after the e being matched.

Unwanted repetition in output from java loop

I am writing a code to reshape the signals. I am getting the output with unwanted repetitions.
INPUT:
String[] rani = {"A","1","2","OK","B","3","4","OK","B","1","3","OK"};
Required OUTPUT:
A/3 B/7 B/4
Got OUTPUT:
A/3 A/3 A/3 A/3 B/7 B/7 B/7 B/7 B/4
ALGORITHM: Single alphabet strings ("A","B" etc.) are followed by number strings ("1","2" etc.). Each alphabet string is to be followed by slash and total of the numbers, and string "OK" is to ignored.
Being newcomer to java and programming I need help to get the needed output.
My code is:
public class SignalOK {
public static void main(String[] arg) {
String finalSignal = "";
String netSignal = "";
String name = "";
int total = 0;
String[] rani = { "A", "1", "2", "OK", "B", "3", "4", "OK", "B", "1",
"3", "OK" };
for (int i = 0; i < rani.length; i++) {
if ((rani[i] == "A") || (rani[i] == "B")) {
name = rani[i];
}
if ((rani[i] == "1") || (rani[i] == "2") || (rani[i] == "3")
|| (rani[i] == "4")) {
total = total + Integer.valueOf(rani[i]);
}
if (rani[i] == "OK") {
netSignal = name + "/" + String.valueOf(total) + " ";
name = "";
total = 0;
}
finalSignal = finalSignal + netSignal;
}
System.out.println(finalSignal);
}
}
Just move the final result string concatenation inside the "OK" if brackets:
if (rani[i].equals("OK")) {
netSignal = name + "/" + String.valueOf(total) + " ";
name = "";
total = 0;
finalSignal = finalSignal + netSignal;
}
Also, always use .equals() to compare strings.
A different approach :-
public static void main(String[] args) {
String[] inputString = {"A","1","2","OK","B","3","4","OK","B","1","3","OK"};
StringBuilder sb = new StringBuilder();
for(String s : inputString)
sb.append(s); // creating a String from array contents
String ss[] = sb.toString().split("OK"); // split on the basis of 'OK'
sb.setLength(0); // emptying the sb, so that it can be used later on also
for(String s : ss){
char[] ch = s.toCharArray();
sb.append(ch[0]); // first alphabet like 'A','B','C'
int val = 0;
for(int i = 1; i< ch.length ; i++)
val +=Integer.parseInt(""+ch[i]); // calculate the int value
sb.append("/"+val+" "); // finally appending alphabet with int value
}
System.out.println(sb);
}
Output :- A/3 B/7 B/4

Categories