Aligning substrings in NSAttributedString - nsattributedstring

I'm writing an attributed string to a UITextView. It has a left-aligned text substring, followed by a line number. I want that line number to be right-aligned.
I tried applying an NSParagraphStyle to the citation string and then appending the citation string to the text string.
let alignStyle = NSMutableParagraphStyle()
alignStyle.alignment = .right
let citationAttributes: Dictionary<NSAttributedString.Key, Any> = [
.paragraphStyle: alignStyle]
let citationString = NSAttributedString(string: citation, attributes: citationAttributes)
textLine.append(citationString)
I expected to see the citation neatly aligned to the right margin, on the same line as the text. But instead, it occurs immediately at the end of the text string.
Is there some way to achieve the formatting result I want with an attributed string?

On another forum I was shown how to add tabs to an attributed string by using its paragraph style. That solved all my problems.
let newLine = NSMutableAttributedString(string: citation + "\t", attributes: citationAttributes)
newLine.append(NSAttributedString(string: line.text + "\n", attributes: textAttributes))
let style = NSMutableParagraphStyle()
style.lineSpacing = lineSpacingValue
let tabStop = tabStopValue
style.tabStops = [NSTextTab(textAlignment: .left, location: tabStop * 1.1, options: [:])]
newLine.addAttribute(.paragraphStyle, value: style, range: NSRange(location: 0, length: newLine.length))

Related

How to remove the new line when reading from UNIX process groovy? [duplicate]

I have a string that contains some text followed by a blank line. What's the best way to keep the part with text, but remove the whitespace newline from the end?
Use String.trim() method to get rid of whitespaces (spaces, new lines etc.) from the beginning and end of the string.
String trimmedString = myString.trim();
String.replaceAll("[\n\r]", "");
This Java code does exactly what is asked in the title of the question, that is "remove newlines from beginning and end of a string-java":
String.replaceAll("^[\n\r]", "").replaceAll("[\n\r]$", "")
Remove newlines only from the end of the line:
String.replaceAll("[\n\r]$", "")
Remove newlines only from the beginning of the line:
String.replaceAll("^[\n\r]", "")
tl;dr
String cleanString = dirtyString.strip() ; // Call new `String::string` method.
String::strip…
The old String::trim method has a strange definition of whitespace.
As discussed here, Java 11 adds new strip… methods to the String class. These use a more Unicode-savvy definition of whitespace. See the rules of this definition in the class JavaDoc for Character::isWhitespace.
Example code.
String input = " some Thing ";
System.out.println("before->>"+input+"<<-");
input = input.strip();
System.out.println("after->>"+input+"<<-");
Or you can strip just the leading or just the trailing whitespace.
You do not mention exactly what code point(s) make up your newlines. I imagine your newline is likely included in this list of code points targeted by strip:
It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space ('\u00A0', '\u2007', '\u202F').
It is '\t', U+0009 HORIZONTAL TABULATION.
It is '\n', U+000A LINE FEED.
It is '\u000B', U+000B VERTICAL TABULATION.
It is '\f', U+000C FORM FEED.
It is '\r', U+000D CARRIAGE RETURN.
It is '\u001C', U+001C FILE SEPARATOR.
It is '\u001D', U+001D GROUP SEPARATOR.
It is '\u001E', U+001E RECORD SEPARATOR.
It is '\u001F', U+0
If your string is potentially null, consider using StringUtils.trim() - the null-safe version of String.trim().
If you only want to remove line breaks (not spaces, tabs) at the beginning and end of a String (not inbetween), then you can use this approach:
Use a regular expressions to remove carriage returns (\\r) and line feeds (\\n) from the beginning (^) and ending ($) of a string:
s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "")
Complete Example:
public class RemoveLineBreaks {
public static void main(String[] args) {
var s = "\nHello world\nHello everyone\n";
System.out.println("before: >"+s+"<");
s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "");
System.out.println("after: >"+s+"<");
}
}
It outputs:
before: >
Hello world
Hello everyone
<
after: >Hello world
Hello everyone<
I'm going to add an answer to this as well because, while I had the same question, the provided answer did not suffice. Given some thought, I realized that this can be done very easily with a regular expression.
To remove newlines from the beginning:
// Trim left
String[] a = "\n\nfrom the beginning\n\n".split("^\\n+", 2);
System.out.println("-" + (a.length > 1 ? a[1] : a[0]) + "-");
and end of a string:
// Trim right
String z = "\n\nfrom the end\n\n";
System.out.println("-" + z.split("\\n+$", 2)[0] + "-");
I'm certain that this is not the most performance efficient way of trimming a string. But it does appear to be the cleanest and simplest way to inline such an operation.
Note that the same method can be done to trim any variation and combination of characters from either end as it's a simple regex.
Try this
function replaceNewLine(str) {
return str.replace(/[\n\r]/g, "");
}
String trimStartEnd = "\n TestString1 linebreak1\nlinebreak2\nlinebreak3\n TestString2 \n";
System.out.println("Original String : [" + trimStartEnd + "]");
System.out.println("-----------------------------");
System.out.println("Result String : [" + trimStartEnd.replaceAll("^(\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029])|(\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029])$", "") + "]");
Start of a string = ^ ,
End of a string = $ ,
regex combination = | ,
Linebreak = \r\n|[\n\x0B\x0C\r\u0085\u2028\u2029]
Another elegant solution.
String myString = "\nLogbasex\n";
myString = org.apache.commons.lang3.StringUtils.strip(myString, "\n");
For anyone else looking for answer to the question when dealing with different linebreaks:
string.replaceAll("(\n|\r|\r\n)$", ""); // Java 7
string.replaceAll("\\R$", ""); // Java 8
This should remove exactly the last line break and preserve all other whitespace from string and work with Unix (\n), Windows (\r\n) and old Mac (\r) line breaks: https://stackoverflow.com/a/20056634, https://stackoverflow.com/a/49791415. "\\R" is matcher introduced in Java 8 in Pattern class: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html
This passes these tests:
// Windows:
value = "\r\n test \r\n value \r\n";
assertEquals("\r\n test \r\n value ", value.replaceAll("\\R$", ""));
// Unix:
value = "\n test \n value \n";
assertEquals("\n test \n value ", value.replaceAll("\\R$", ""));
// Old Mac:
value = "\r test \r value \r";
assertEquals("\r test \r value ", value.replaceAll("\\R$", ""));
String text = readFileAsString("textfile.txt");
text = text.replace("\n", "").replace("\r", "");

How to Store All Text in Between Two Index Positions of Same String in VBScript?

So I am going off memory here because I cannot see the code I am trying to figure this out for at the moment, but I am working with some old VB Script code where there is a data connection that is set like this:
set objCommand = Server.CreateObject("ADODB.command")
and I have a field from the database that is being stored in a variable like this:
Items = RsData(“Item”).
This specific field in the database is a long string of
text:
(i.e. “This is part of a string of text…Header One: Here is text after header one… Header Two: Here is more text after header two”).
There are certain parts of the text that I wish to store as a variable that are between two index positions in the long string of text within that field. They are separated by headers that are stored in the text field above like this: “Header One:” and “Header Two:”, and I want to capture all text that occurs in between those two headers of text and store them into their own variable (i.e. “Here is text after header one…”).
How do I achieve this? I have tried to use the InStr method to set the index but from how I understand how this works it will only count the beginning of where a specific part of the string occurs. Am I wrong in my thinking of this? Since that is the case, I am also having trouble getting the Mid function to work. Can some one please show me an example of how this is supposed to work? Remember, I am only going off of memory so please forgive me that I am unable to provide better code examples now. I hope my question makes sense!
I am hopeful that someone can help me with an answer tonight so I can try this out tomorrow when I am near the code again! Thank you for your efforts and any help offered!
You can extract all the substrings starting with the text Header and ending just before either the next Header or end-of-string. I have used regular expression to implement that and it is working for me. Have a look at the code below. If I get a simpler(non-regex solution), I will update the answer.
Code:
strTest = "Header One: Some random text Header Two: Some more text Header One: Some random textwerwerwefvxcf234234 Header Three: Some more t2345fsdfext Header Four: Some randsdfsdf3w42343om text Header Five: Some more text 123213"
set objReg = new Regexp
objReg.Global = true
objReg.IgnoreCase = false
objReg.pattern = "Header[^:]+:([\s\S]*?)(?=Header|$)" '<---Regex Pattern. Explained later.
set objMatches = objReg.Execute(strTest)
Dim arrHeaderValues() '<-----This array contains all the required values
i=-1
for each objMatch in objMatches
i = i+1
Redim Preserve arrHeaderValues(i)
arrHeaderValues(i) = objMatch.subMatches.item(0) '<---item(0) indicates the 1st group of each match
next
'Displaying the array values
for i=0 to ubound(arrHeaderValues)
msgbox arrHeaderValues(i)
next
set objReg = Nothing
Regex Explanation:
Header - matches Header literally
[^:]+: - matches 1+ occurrences of any character that is not a :. This is then followed by matching a :. So far, keeping the above 2 points in mind, we have matched strings like Header One:, Header Two:, Header blabla123: etc. Now, whatever comes after this match is relevant to us. So we will capture that inside a Group as shown in the next breakup.
([\s\S]*?)(?=Header|$) - matches and captures everything(including newlines) until either the next Header or the end-of-the-string(represented by $)
([\s\S]*?) - matches 0+ occurrences of any character and capture the whole match in Group 1
(?=Header|$) - match and capture the above thing until another instance of the string Header or end of the string
Click for Regex Demo
Alternative Solution(non-regex):
strTest = "Header One: Some random text Header Two: Some more text Header One: Some random textwerwerwefvxcf234234 Header Three: Some more t2345fsdfext Header Four: Some randsdfsdf3w42343om text Header Five: Some more text 123213"
arrTemp = split(strTest,"Header") 'Split using the text Header
j=-1
Dim arrHeaderValues()
for i=0 to ubound(arrTemp)
strTemp = arrTemp(i)
intTemp = instr(1,strTemp,":") 'Find the position of : in each array value
if(intTemp>0) then
j = j+1
Redim preserve arrHeaderValues(j)
arrHeaderValues(j) = mid(strTemp,intTemp+1) 'Store the desired value in array
end if
next
'Displaying the array values
for i=0 to ubound(arrHeaderValues)
msgbox arrHeaderValues(i)
next
If you don't want to store the values in an array, you can use Execute statement to create variables with different names during run-time and store the values in them. See this and this for reference.

issue related to space after link

I am generating a link using below code
string EncryptPath = Common.Encrypt(Path);
string SourceLinkPath= string.Empty;
if (File.Exists(Server.MapPath("Image.txt")))
{
SourceLinkPath = System.IO.File.ReadAllText(Server.MapPath ("Image.txt"));
}
string link2 = SourceLinkPath + EncryptPath;
TxtPathLink2.Text = link2;
the link is generating but it is giving space after sourcepath. OUTPUT like
http://18.10.10.11/test/View.aspx?Value=
67534ERT
i want to generate like http://18.10.10.11/test/View.aspx?Value=67534ERT
How can i generate link in one line
The .txt file probably has a whitespace you are missing.
Change System.IO.File.ReadAllText(Server.MapPath ("Image.txt"))
To:
System.IO.File.ReadAllText(Server.MapPath("Image.txt")).Trim()
String.Trim() removes all leading and trailing white-space characters from the String object.

How to place underline on space string in ITextSharp

How to add under line under a spacebar. It is not adding space under the empty spaces.
I tried with 2-3 example and it failed to add underline under space.
1.
para = New Paragraph(New Chunk("abc. ", underlined_font))
cell = New PdfPCell(para)
cell.Border = 0
cell.BorderWidthBottom = 0
document.Add(cell)
Dim str_required_space As New String(" "c, 20)
para = New Paragraph(New Chunk(str_required_space, underlined_font))
cell = New PdfPCell(para)
cell.Border = 0
cell.BorderWidthBottom = 0
document.Add(cell)
I can't use border of cell as the length of the input string is uncertain. So I am using underline.
Please help to add spaces under space.
My Requirement image
Thanks
[Edit]
If I follow answer 1 then result would be like below
asdasd asdsad scasdnk kjashdk kasbas ckasbd ascuasc ksajcasc
asdansjdnasjakjsnasndasdmlaskdm
________________________________________________________________
But I need Below result.
asdasd asdsad scasdnk kjashdk kasbas ckasbd ascuasc ksajcasc
________________________________________________________________
asdansjdnasjakjsnasndasdmlaskdm
________________________________________________________________
I tried with Ansii Code. Not working for me :(
Dim str_required_space As New String(ChrW(32), (119 - (str_synopsis.Length Mod 119)))
para = New Paragraph(str_required_space)
cell = New PdfPCell(para)
cell.Border = 0
doc.Add(cell)
Please read chapter 2 of my book, more specifically the section about vertical position marks, separators, and tabs (section 2.2.6).
Looking at your image (ignoring the soft porn images on that site, please avoid such links in the future), I think you need a line as shown in figure 2.9 (the line under the names of the directors). The code that results in the PDF shown in that screen shot can be found here.
This is how it's done in Java:
Paragraph p = new Paragraph("abc.");
LineSeparator line = new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -2);
p.add(line);
document.add(p);
It should be a no-brainer to adapt this code to C#. If you do experience problems, then you can find the ported versions of the book samples here.
What did you do wrong in your code?
This doesn't make sense:
para = New Paragraph(New Chunk("abc. ", underlined_font))
The content of the Chunk is trimmed, which explains why the spaces disappear. An alternative would be to use non-breaking space characters (ASCII code 160) instead of regular space characters (ASCII code 32).
Update
My previous answer was based on your image and it was the correct answer to your initial question. However: you have now changed your question (instead of creating a new question).
You can meet your requirement by using a page event, more specifically, by implementing the OnGenericTag() method. This method is described in chapter 5 of my book.
In Java, the implementation would look like this:
public void onGenericTag(PdfWriter writer, Document pdfDocument,
Rectangle rect, String text) {
Rectangle page = pdfDocument.getPageSize();
float x1 = page.getRight(pdfDocument.rightMargin());
float x2 = page.getLeft(pdfDocument.leftMargin());
float y = rect.getBottom() - 3;
PdfContentByte canvas = writer.getDirectContent();
canvas.moveTo(x1, y);
canvas.lineTo(x2, y);
canvas.stroke();
}
You need to create an instance of the page event with that implementation (e.g. a class that you wrote and that you named MyPageEvent) and declare that page event to the PdfWriter using the setPageEvent() method:
writer.setPageEvent(new MyPageEvent());
You can now declare you Chunk and Paragraph like this:
Chunk chunk = new Chunk(long_text);
chunk.setGenericTag("");
Paragraph p = new Paragraph(chunk);
document.add(p);
It is important that you construct your paragraph with only one Chunk object. If you have more than one Chunk in the paragraph, parts of the line will look thicker.

How does google elegantizr work?

So I was browsing through google's april fool's jokes, and I found this one
http://www.google.com/landing/elegantizr/
Which claims to load super fast css, but does this instead
http://shodor.org/~amalani/elegantizr.html
using this code
:before {
content: '\41\50\52\49\4C\20\46\4F\4F\4C\20\F4\BF\F4';
}
What format is this, and how does it work?
The content property specifies content to insert into your html. It must be paired with either the :before or :after selector in order to specify where that content would be inserted. Intended use is that the before or after selector is applied to an element. For example:
.copyright:before {content: "\00A9 ";}
Would add a copyright symbol to the front of every element with the class "copyright". CSS has it's own way of doing what in HTML are character entities. More info can be found # css-tricks.com/css-content/. This is where I learned most of what I know about it.
In this case, though, they did not specify which element to apply this to, therefor, it is applied to all elements.
So the character codes used in the elegantizer are as follows:
\41 = A
\50 = P
\52 = R
\49 = I
\4C = L
\20 = space
\46 = F
\4F = O
\4F = O
\4C = L
\20 = S
\F4 = ô
\BF = ¿
\F4 = ô
A full list of unicode characters can be found at the List of Unicode Characters Wiki. Simply remove the leading zeros and precede them with a backslash.

Resources