Replacing text in stringbuffer without hardcoding indexes - string

I have a Stringbuffer object which contains data "Detail is:"
Based on the result of a HashMap(Map), I populate the details below this line with help of looping through the map and fetching data.
Now I want to replace the text "Detail is:" with "Details are:" if more than one record is fetched.
Is their any way to achieve this?
Thanks

You can:
Get the string out of the stringbuffer.
Reset the stringbuffer and write the new beginning.
Write all after the replaced Prefix back to the buffer.
Instead, you could also do this:
Omit the Prefix in the first place
Do a simple string-concatenation at the end.

You can even do like this if Map size is greater than 1
StringBuffer sb=new StringBuffer();
if(map.size>1){
sb.append("Details are:")
}else{
sb.append("Details is:");
}

Related

String formating and store the values

I have a string similar to below
"OPR_NAME:CODE=value,:DESC=value,:NUMBER=value,:INITIATOR=value,:RESP"
I am using StringTokenizer to split the string into tokens based on the delimiter(,:),I need the values of
CODE,DESC and NUMBER.
Can someone pls tell how to achieve this ? The values may come in random order in my string
For eg my string may be like below as well :
"OPR_NAME:DESC=value,:NUMBER=value,:CODE=value,:INITIATOR=value,:RESP" and still it should be able to fetch the values.
I did below to split the string into tokens
StringTokenizer st = new StringTokenizer(str,",:");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
But not sure how to store these tokens to just get the value of 3 fields as mentioned above.
Thanks !!
Okay so what I meant is, detect where is the "=" and then apply a substring to get the value you want.
rough example
System.out.println(st.nextToken().substring(st.nextToken().indexOf('=')+1,st.nextToken().length()));
Use split instead :
String[] parts = X.split(",:");
for (String x:parts) {
System.out.println(x.substring(x.indexOf('=')+1));
}

Reading a text file into an structure

I'm trying to read some information from a .txt file and then store it in a structure, but I don't know how to do it only selecting the words I need.
The .txt is the following
fstream write_messages("C:\\Messages.txt");
A line in the .txt looks like this:
18 [#deniseeee]: hello, how are you? 2016-04-26.23:37:58
So, the thing is that I have a list of strutures
list<Message*> g_messages;
where
struct Message {
static unsigned int s_last_id; // keep track of IDs to assign it automatically
unsigned int id;
string user_name;
string content;
string hour;
Message(const string& a_user_name, const string& a_content) :
user_name(a_user_name), content(a_content), id(++s_last_id), hour(currentDateTime())
{
}
Message(){}
};
I want to read the file so that I can store the number into the id of the list, the word between "[#" and "]:" into the user_name, the next sentence into content and the date into the hour.
How can I do this?
Any help is appreciated
Thank you
The problem is: you are writing this file so it is easy to read by a person, while you should write it so it is easy to load by your program.
You are using spaces to separate your elements, while spaces can very well happen inside those elements.
I would suggest to use a symbol that is not likely to be used in the text, for example the pipe '|'. Also, I would write fixed-size elements first:
18|2016-04-26.23:37:58|deniseeee|hello, how are you?
Then you can read entire line, split it on those pipe symbols and load into your struct fields.

Splitting string for LatLng object

I am stuck on a very annoying problem. Here is what I am trying to achieve. I read the latitude and longitude in two text boxes and then split each of the pair on a comma as that is what they are separated by. Then I need to parse them and create a LatLng object to create a Google marker. My problem for some reason is splitting the string. I know that all I need to do is use String.split() method to achieve it. Here is what I do:
Lets say the value in text box is 26.2338, 81.2336
//Reading the value in text boxes on HTML form
var sourceLocation =document.getElementById("source").value;
//Remove any spaces in between coordinates
var newString =sourceLocation.replace(/\s/g, '');
//Split the string on ,
newString.split(",");
//Creating latitude longitude objects of the source and destination
var newLoc =new google.maps.LatLng(parseFloat(newString[0]),parseFloat(newString[1]));
Now I am unable to understand as to why newString[0] just gives me 2 while it should give 26.2338. Similarly, newString[1] gives 6 instead of 81.2336. What am I doing wrong?? Any help will be greatly appreciated.
String.split() returns an array, it doesn't modify the string to somehow make it into an array. You want
var parts = newString.split(",");
var newLoc = new google.maps.LatLng(parseFloat(parts[0]),parseFloat(parts[1]));

Seperated text line in Apache POI XWPFRun object

I 'm trying to replace a template DOCX document with Apache POI by using the XWPFDocument class. I have tags in the doc and a JSON file to read the replacement data. My problem is that a text line seems separated in a certain way in DOCX when I change its extension to ZIP file and open document.xml. For example [MEMBER_CONTACT_INFO] text becomes [MEMBER_CONTACT_INFO and ] separately. POI reads this in the same way since the DOCX original is like this. This creates 2 XWPFRun objects in the paragraph which show the text as [MEMBER_CONTACT_INFO and ] separately.
My question is, is there a way to force POI to run like Word via merging related runs or something like that? Or how can I solve this problem? I 'm matching run texts while replacing and I can't find my tag because it is split into 2 different run object.
Best
This wasted so much of my time once...
Basically, an XWPFParagraph is composed of multiple XWPFRuns, and XWPFRun is a contagious text that has a fixed same style.
So when you try writing something like "[PLACEHOLDER_NAME]" in MS-Word it will create a single XWPFRun. But if you somehow add a few things more, and then you go back and change "[PLACEHOLDER_NAME]" to something else it is never guaranteed that it will remain a single XWPFRun it is quite possible that it will split to two Runs. AFAIK this is how MS-Word works.
How to avoid splitting of Runs in such cases?
Solution: There are two solutions that I know of:
Copy text "[PLACEHOLDER_NAME]" to Notepad or something. Make your necessary modification and copy it back and paste it instead of "[PLACEHOLDER_NAME]" in your word file, this way your whole "[PLACEHOLDER_NAME]" will be replaced with new text avoiding splitting of XWPFRuns.
Select "[PLACEHOLDER_NAME]" and then click of MS-Word "Replace" option and Replace with "[Your-new-edited-placeholder]" and this will guarantee that your new placeholder will consume a single XWPFRun.
If you have to change your new placeholder again, follow step 1 or 2.
Here is the java code to fix that separate text line issue. It will also handle the mult-format string replacement.
public static void replaceString(XWPFDocument doc, String search, String replace) throws Exception{
for (XWPFParagraph p : doc.getParagraphs()) {
List<XWPFRun> runs = p.getRuns();
List<Integer> group = new ArrayList<Integer>();
if (runs != null) {
String groupText = search;
for (int i=0 ; i<runs.size(); i++) {
XWPFRun r = runs.get(i);
String text = r.getText(0);
if (text != null)
if(text.contains(search)) {
String safeToUseInReplaceAllString = Pattern.quote(search);
text = text.replaceAll(safeToUseInReplaceAllString, replace);
r.setText(text, 0);
}
else if(groupText.startsWith(text)){
group.add(i);
groupText = groupText.substring(text.length());
if(groupText.isEmpty()){
runs.get(group.get(0)).setText(replace, 0);
for(int j = 1; j<group.size(); j++){
p.removeRun(group.get(j));
}
group.clear();
groupText = search;
}
}else{
group.clear();
groupText = search;
}
}
}
}
for (XWPFTable tbl : doc.getTables()) {
for (XWPFTableRow row : tbl.getRows()) {
for (XWPFTableCell cell : row.getTableCells()) {
for (XWPFParagraph p : cell.getParagraphs()) {
for (XWPFRun r : p.getRuns()) {
String text = r.getText(0);
if (text.contains(search)) {
String safeToUseInReplaceAllString = Pattern.quote(search);
text = text.replaceAll(safeToUseInReplaceAllString, replace);
r.setText(text);
}
}
}
}
}
}
}
For me it didn't work as I expected (every time). In my case I used "${PLACEHOLDER} in the text. At first we need to take a look how Apache Poi recognize each Paragraph which we want to iterate through with Runs. If you go deeper with docx file construction you will know that one run is a sequence of characters of text with the same font style/font size/colour/bold/italic etc. That way placeholder sometimes was divided into parts OR sometimes whole paragraph was recognized as a one Run and it was impossible to iterate through words. What I did is to bold placeholder name in a template document. Than when iterating through RUN I was able to iterate through whole placeholder name ${PLACEHOLDER}. When I replaced that value with
for (XWPFRun r : p.getRuns()) {
String text = r.getText(0);
if (text != null && text.contains("originalText")) {
text = text.replace("originalText", "newText");
r.setText(text,0);
}
}
I've added just r.isBold(false); after setText.
That way placeholder is recognized as a different run -> I'm able to replace specific placeholder, and in the processed document I have no bolding, just a plain text. For me one of a additional advantage was that visualy I'm able to faster find placeholders in text.
So finally above loop looks like that:
for (XWPFRun r : p.getRuns()) {
String text = r.getText(0);
if (text != null && text.contains("originalText")) {
text = text.replace("originalText", "newText");
r.setText(text,0);
r.isBold(false);
}
}
I hope it will help to someone, while I spend too much time for that :)
I also had this issue few days ago and I couldn't find any solution. I chose to use PLACEHOLDER_NAME instead of [PLACEHOLDER_NAME]. This is working fine for me and it's seen like a single XWPFRun object.
To be sure that a word will be consider as a single XWPFRun,
You can use merge_field as variable in word like that
Place cursor on the word you want to be a single run.
Press CTRL and F9 together and { } in gray will appear.
Right-click on the { } field and select Edit Field.
In pop-up box, select Mail Merge from Categories and then MergeField from Field Names.
Click OK.

Is there any way to retrieve a appended int value to a String in javaScript?

I am currently working on a project that dynamically displays DB content into table.
To edit the table contents i am want to use the dynamically created "string"+id value.
Is there any way to retrieve the appended int value from the whole string in javaScript?
Any suggestions would be appreciative...
Thanks!!!
If you know that the string part is only going to consist of letters or non-numeric characters, you could use a regular expression:
var str = "something123"
var id = str.replace(/^[^\d]+/i, "");
If it can consist of numbers as well, then things get complicated unless you can ensure that string always ends with a non-numeric character. In which case, you can do something like this:
var str = "something123"
var id = str.match(/\d+$/) ? str.match(/\d+$/)[0] : "";
(''+string.match(/\d+/) || '')
Explanation: match all digits in the variable string, and make a string from it (''+).
If there is no match, it would return null, but thanks to || '', it will always be a string.
You might try using the regex:
/\d+$/
to retrieve the appended number

Resources