Am I missing something here ? XD TrimRight does not seem to want to work - trim

Ok, here is the small portion of code to demonstrate:
CString txt = _T("Hello World");
CString txt2 = txt;
txt2.TrimRight('W');
AfxMessageBox(txt2);
The output is "Hello World".
What am I not getting right ?

The call txt2.TrimRight('W'); removes all characters 'W' from the right side of the string. Since "Hello World" does not end in 'W' nothing is trimmed at all.

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", "");

Why is a Base64 string displayed as empty in Message Box?

I have to encode some HTML source code into base64 format before form submission, and then decode it back to original code in the code behind. Here is the testing code by MsgBox:
MsgBox(HttpContext.Current.Request.Form("encodedSourceCode"))
MsgBox(Convert.ToString(HttpContext.Current.Request.Form("encodedSourceCode").GetType()))
Dim b = Convert.FromBase64String(HttpContext.Current.Request.Form("encodedSourceCode"))
Dim html = System.Text.Encoding.UTF8.GetString(b)
MsgBox(html)
And I have added an alert() for encodedSourceCode in client script.
The results turn out to be:
First MsgBox: Empty
Second MsgBox: "System.String"
Last MsgBox: Original HTML source code
And the JS alert dialog shows the base64 string, which consists of a bunch of digits and alphabets.
In short, everything is fine, except the first MsgBox, which is supposed to be base64 encoded string but turns out to be empty. Why? Is it normal?
Actually it does not matter much because even the final result (after decoding) seems to have no problem, but I'm just curious why the interim result is not shown as what it's supposed to be.
It seems that the string is simply too long without 'wrappable' characters, I suppose. MsgBox cuts out the 'last word' and shows nothing.
This may confirm it:
dim test = HttpContext.Current.Request.Form("encodedSourceCode")
MsgBox(test) ' empty
test = test.Substring(0, 20)
MsgBox(test) ' shows the first 20 characters
Testing in LinqPad, I get the limit around 43.000 characters:
MsgBox("".PadLeft(43000, "a"))
MsgBox("".PadLeft(44000, "a"))
MsgBox("".PadLeft(43000, "a") & " " & "".PadLeft(1000, "a"))
1st: shows text.
2nd: shows empty box, length = 44.000
3rd: shows text, although the total length is 44.001, but wrappable at the space.
It definitely has nothing to do with base64 strings as they are simple strings. Here the proof:
Dim myString = "Hello world, this is just an ɇxâmpŀƏ ʬith some non-ansi characters..."
Dim myEncoding As Encoding = Encoding.UTF8
MsgBox(myString)
Dim myBase64 = Convert.ToBase64String(myEncoding.GetBytes(myString))
MsgBox(myBase64)
Dim myStringAgain = myEncoding.GetString(Convert.FromBase64String(myBase64))
MsgBox(myStringAgain)
MsgBox(If(StringComparer.Ordinal.Equals(myString, myStringAgain), "same", "different"))
The line
MsgBox(Convert.ToString(HttpContext.Current.Request.Form("encodedSourceCode").GetType()))
results in "System.String" because you convert the name of the type to a string (see xxx.GetType()).

ASP.net VB String builder double double quotes [duplicate]

Everytime I add CharW(34) to a string it adds two "" symbols
Example:
text = "Hello," + Char(34) + "World" + Char(34)
Result of text
"Hello,""World"""
How can I just add one " symbol?
e.g Ideal result would be:
"Hello,"World""
I have also tried:
text = "Hello,""World"""
But I still get the double " Symbols
Furthermore. Adding a CharW(39), which is a ' symbol only produces one?
e.g
text = "Hello," + Char(39) + "World" + Char(39)
Result
"Hello,'World'"
Why is this only behaving abnormally for double quotes? and how can I add just ONE rather than two?
Assuming you meant the old Chr function rather than Char (which is a type).It does not add two quotation mark characters. It only adds one. If you output the string to the screen or a file, you would see that it only adds one. The Visual Studio debugger, however, displays the VB-string-literal representation of the value rather than the raw string value itself. Since the way to escape a double-quote character in a string is to put two in a row, that's the way it displays it. For instance, your code:
text = "Hello," + Chr(34) + "World" + Chr(34)
Can also be written more simply as:
text = "Hello,""World"""
So, the debugger is just displaying it in that VB syntax, just as in C#, the debugger would display the value as "Hello, \"World\"".
The text doesn't really have double quotes in it. The debugger is quoting the text so that it appears as it would in your source code. If you were to do this same thing in C#, embedded new lines are displayed using it's source code formatting.
Instead of using the debugger's output, you can add a statement in your source to display the value in the debug window.
Diagnostics.Debug.WriteLine(text)
This should only show the single set of quotes.
Well it's Very eazy
just use this : ControlChars.Quote
"Hello, " & ControlChars.Quote & "World" & ControlChars.Quote

Commenting ASP.Net code when using the '_' character

This might be a really easy one but I couldn't seem to find an answer anywhere
I'm trying to comment my code as follows
Session("test") = "JAMIE" _
'TEST INFO
& "TEST" _
'ADDRESS INFO
& "ADDRESS = TEST"
With the code above i'm getting the error
Syntax error
But when I remove the comments like so
Session("test") = "JAMIE" _
& "TEST" _
& "ADDRESS = TEST"
It works fine so my guess is that I cannot comment my code between the _ character.
Is there some way I can get around this as I'd like to comment my code ideally
The _ character is the line continuation. It means that the next line is interpreted as if it was on the same line.
So, putting a comment in the middle of the line is a syntax error.
Since you want a solution:
Either put a comment before the continued line or after it
As Tim Schmelter points out in his answer, you can construct the value that will go into the Session object before you put it into the Session object - you can do that is separate statements and comment those to your hearts content.
As Oded has mentioned, The _ character continues the line so you cannot comment between.
You could write:
Dim value = "JAMIE"
'TEST INFO
value &= "TEST"
'ADDRESS INFO
value &= "ADDRESS = TEST"
Session("test") = value
Because that may create separate strings internally just to comment them, you could use a StringBuilder here. You could show us what you're really tring to do, so that we can suggest a different approach(if you need to comment each "line" of a single variable, you should consider to redesign the way you assign the value to the variable).
System.Text.StringBuilder str = new System.Text.StringBuilder();
str.Append("JAMIE");
str.Append("TEST");//TEST INFO
str.Append("ADDRESS");//ADDRESS INFO
public string Test
{
get
{
return Convert.ToString(Session["TEST"]);
}
set
{
Session["Test"] = value;
}
}
Test = st.ToString();

Multiline Text in Flex 4

In Flex I want to create a Text file and it is working, but the problem is all inputs are written in one line;
here the cods
addText.text="[ \r\n"
addText.text=addText.text+"] \r\n";
fileRef.save(addText.text, "data.txt");
the current result is like below;
[]
how can I make it like this;
[
]
i would start trying
addTextxt.text = "[ \n ]";
it normally works in all cases...
good luck ( :

Resources