Java string stop the escape character action - java

My question is suppose I have a string and a string builder:
String sample = "Ran\"dom";
StringBuilder sb = new StringBuilder("Hello");
On appending the sample string to the StringBuilder and printing the String builder, it returns "HelloRan"dom"
Here the purpose of "\" in sample would be to escape the " character. But, I do not want that action to happen. I want the output of sb after appending sample to be "HelloRan\"dom". How do I do that.

You need to escape the whole "\"" with another "\".
Try,
String sample = "Ran\\\"dom";
You can learn more about escape characters from https://www.freeformatter.com/java-dotnet-escape.html

Related

Java: Reverse string via a delimiter

I am trying to reverse the characters in a string separated by a delimiter I provide.
Input: string: "Abc.134dsq" , delimiter: "."
Desired Output: cbA.qsd431
My attempt:
String fileContent = "Abc.134dsq";
String delimiter = ".";
fileContent = fileContent.replace(delimiter, "-");
String[] splitWords = fileContent.split("-");
StringBuilder stringBuilder = new StringBuilder();
for (String word : splitWords) {
StringBuilder output = new StringBuilder(word).reverse();
stringBuilder.append(output);
}
System.out.println(stringBuilder.toString());
Try this:
System.out.println(Arrays
.stream("Abc.134dsq".split("\\.", -1))
.map(StringBuilder::new)
.map(StringBuilder::reverse)
.collect(Collectors.joining(".")));
See live demo.
This handles the “preserving the trailing dot” scenarios mentioned in the comments. Live demo shows this aspect too.
Enough time has passed that your homework deadline has passed, so I thought I’d show you this one-liner.

replacing \n in a String

There are several answers to similar questions as mine, but I have tried several of them and they are not working. I must be doing something stupid.
I have
String newline = System.getProperty("line.separator");
String content = "Test\n another line\n";
if(content.contains("\\n")) {
content = content.replaceAll("(\\n)", newline);
System.out.print(content);
}
I also tried "\n" and "\\n" in the regex. The content remains unchanged using replaceAll.
Okay facts:
\r is a CR, U+000D
\n is a LF, U+000A
Those characters you can put in a String
String s = "line 1.\nline 2.\n";
String newline = System.getProperty("line.separator");
newline can be "\n" (1 char) or "\r\n" (2 chars) or still something else.
If you would read this text, reading first a backslash and then an n, it would be in code:
String nl = "\\n"; // Two chars, an escaped backslash and a `n`.
String nl = "\\" + 'n'; // Two chars, an escaped backslash and a `n`.
If you would want to replace these two chars with a real newline:
s = s.replace("\\n", "\n");
s = s.replace("\\n", newline); // Platform dependent
Now java regex is still more complex, as it escapes regex letters with a backslash, which in Strings is escaped itself:
You will not need a regex replaceAll/replaceFirst here, but it would go as:
s = s.replaceAll("\\\\n", "\n");
The pattern containing two backslashes: regex escaping of one backslash.
String newline = System.getProperty("line.separator");
String content = "Test\\n another line\\n";
if(content.contains("\\n")) {
content = content.replaceAll("\\\\n", newline);
System.out.print(content);
}
The extra 2 slashes are the escape characters
I also tried this and it works
content.replace("\\n", "\\r\\n")
but
content.replaceAll("\\n", "\\r\\n")
does not.
So in the end I used
while(content.contains("\\n")) {
content = content.replace("\\n", newline);
}
And this solves my problem, not elegant, but it works.

Java BufferedReader miss some values

I have problem with BufferedReader.
My source code works fine, but the problem is when I read a value from named pipe it missed some values.
delim="\t";
reader = new BufferedReader(new FileReader("/tmp/base.pip"));
while ((line = reader.readLine())!=null) {
try{
timestamp = Long.parseLong(line.split(delim)[0]);
}
catch(Exception e){
continue;
}
I need to read whole line to get first column value properly.
example
original line : 12345678 A B
readed line: 2345678 A B (missed first bit)
Is there any suggestion to solve this problem?
p.s it works fine, but only a few lines have problem like the above examples.
I've tested your program and it works fine on my computer.
Check your delim String delim = "\t"
Check your file and it has a tab seperator between them.
Check the line value in your program.
If you don't have a tab space, consider using a regular expression which accepts any number of spaces.
String delim = "\\s+";
delim = '\t'
Split cannot take a character as a delimiter. Please check that. It has to be delim = "\t"
Try to split it with Whitspaces and take the first out ouf the array like:
delim = "\\s";
timestamp = Long.parseLong(line.split(delim)[0]);
I think this should solve your problem.

Java subString confusion

i was doing a small java code where data is read through a file and stored in a String
and then using subStrig i have to break this string ,
For example data is saved like this "Hello java $" "Hello word $" , each sentence contains $ at the end and i want to break it on the basis of $
I did try using indexOf , lastindexOf etc but was not able to do exact logic , pleas help me
BufferedReader br= new BufferedReader(new FileReader("c:\\javaprograms\\a.txt));
while((a=br.readLine())!=null)
{
s=s+a;
// here i have to split the data that is "Hello java$" "Hello world$"
}
Maybe it would be better to use a Scanner with custom delimiter?
For example like this:
BufferedReader br = new BufferedReader(new FileReader("..."));
Scanner sc = new Scanner(br);
sc.useDelimiter("\\$");
while (sc.hasNext())
{
String text = sc.next();
System.out.println(text);
...
}
This code splits your text with "$" as delimiter
Works fine for me:
String a = "Hello java $ fff";
System.out.println(a.indexOf("$"));
System.out.println(a.substring(0, a.indexOf("$")));
Output:
11
Hello java
You want to look into the split() function in the String class, this will allow you to return an array of Strings split around a particular String or regex.

Conversion from javascript-escaped Unicode to Java Unicode

I have a query string passed in through an HTTP request that has this character in it:
%u54E6
And I'd like to generate a string that contains the actual Chinese character so I can use it in a different part of the application, I've tried using this code:
String foo = "%u54E6";
String ufoo = new String(foo.replaceAll("%u([a-zA-Z0-9]{4})", "\\" + "u$1"));
System.out.println("ufoo: " + ufoo);
Unfortunately, all I'm getting is 'u54E6' printed to the console for the value, instead of the Chinese character.
Is there an easy way to convert the original string to a Unicode character in Java?
You're trying to use \u escapes at run time. These are compile-time only. Instead, you should be able to do something like:
String foo = "%u54E6";
Pattern p = Pattern.compile("%u([a-zA-Z0-9]{4})");
Matcher m = p.matcher(foo);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb,
String.valueOf((char) Integer.parseInt(m.group(1), 16)));
}
m.appendTail(sb);
System.out.println(sb.toString());

Categories