How can I make Java print quotes, like "Hello"? - java

How can I make Java print "Hello"?
When I type System.out.print("Hello"); the output will be Hello. What I am looking for is "Hello" with the quotes("").

System.out.print("\"Hello\"");
The double quote character has to be escaped with a backslash in a Java string literal. Other characters that need special treatment include:
Carriage return and newline: "\r" and "\n"
Backslash: "\\"
Single quote: "\'"
Horizontal tab and form feed: "\t" and "\f"
The complete list of Java string and character literal escapes may be found in the section 3.10.6 of the JLS.
It is also worth noting that you can include arbitrary Unicode characters in your source code using Unicode escape sequences of the form \uxxxx where the xs are hexadecimal digits. However, these are different from ordinary string and character escapes in that you can use them anywhere in a Java program ... not just in string and character literals; see JLS sections 3.1, 3.2 and 3.3 for a details on the use of Unicode in Java source code.
See also:
The Oracle Java Tutorial: Numbers and Strings - Characters
In Java, is there a way to write a string literal without having to escape quotes? (Answer: No)

char ch='"';
System.out.println(ch + "String" + ch);
Or
System.out.println('"' + "ASHISH" + '"');

Escape double-quotes in your string: "\"Hello\""
More on the topic (check 'Escape Sequences' part)

You can do it using a unicode character also
System.out.print('\u0022' + "Hello" + '\u0022');

Adding the actual quote characters is only a tiny fraction of the problem; once you have done that, you are likely to face the real problem: what happens if the string already contains quotes, or line feeds, or other unprintable characters?
The following method will take care of everything:
public static String escapeForJava( String value, boolean quote )
{
StringBuilder builder = new StringBuilder();
if( quote )
builder.append( "\"" );
for( char c : value.toCharArray() )
{
if( c == '\'' )
builder.append( "\\'" );
else if ( c == '\"' )
builder.append( "\\\"" );
else if( c == '\r' )
builder.append( "\\r" );
else if( c == '\n' )
builder.append( "\\n" );
else if( c == '\t' )
builder.append( "\\t" );
else if( c < 32 || c >= 127 )
builder.append( String.format( "\\u%04x", (int)c ) );
else
builder.append( c );
}
if( quote )
builder.append( "\"" );
return builder.toString();
}

System.out.println("\"Hello\"");

System.out.println("\"Hello\"")

There are two easy methods:
Use backslash \ before double quotes.
Use two single quotes instead of double quotes like '' instead of "
For example:
System.out.println("\"Hello\"");
System.out.println("''Hello''");

Take note, there are a few certain things to take note when running backslashes with specific characters.
System.out.println("Hello\\\");
The output above will be:
Hello\
System.out.println(" Hello\" ");
The output above will be:
Hello"

Use Escape sequence.
\"Hello\"
This will print "Hello".

you can use json serialization utils to quote a java String.
like this:
public class Test{
public static String quote(String a){
return JSON.toJsonString(a)
}
}
if input is:hello output will be: "hello"
if you want to implement the function by self:
it maybe like this:
public static String quotes(String origin) {
// 所有的 \ -> \\ 用正则表达为: \\ => \\\\" 再用双引号quote起来: \\\\ ==> \\\\\\\\"
origin = origin.replaceAll("\\\\", "\\\\\\\\");
// " -> \" regExt: \" => \\\" quote to param: \\\" ==> \\\\\\\"
origin = origin.replaceAll("\"", "\\\\\\\"");
// carriage return: -> \n \\\n
origin = origin.replaceAll("\\n", "\\\\\\n");
// tab -> \t
origin = origin.replaceAll("\\t", "\\\\\\t");
return origin;
}
the above implementation will quote escape character in string but exclude
the " at the start and end.
the above implementation is incomplete. if other escape character you need , you can add to it.

Related

how to escape escape characters in Java

I have a large file that contains \' that I need to find. I've tried variations of the following but it's not working:
do{
line = TextFileIO.readLine(bufferedReader);
if(line != null){
TextFileIO.writeLine(bufferedWriter,line);
for (int i = 0; i < line.length() - 1; i++){
if(line.substring(i,i+1).equals("\\\'"))System.out.println("we found it " + line);
}
}
}while (line != null);
No need to escape the single quote!
Single quotes don't need escaping because all Java strings are delimited by double quotes. Single quotes delimit character literals. So in a character literal, you need to escape single quotes, e.g. '\''.
So all you need is "\\'", escaping only the backslash.
substring(i,i+1) cannot produce a two character string. If you are trying to get 2-character strings, you need to call with (i,i+2).
Also, your for loop can be replaced by a call to contains.
if(line.contains("\\'"))System.out.println("we found it " + line);
To represent a single backslash followed by an apostrophe, you can use
"\\'"
But there is no way substring(i,i+1) can be equal to a two-character string.
Perhaps you mean
if (line.substring(i, i+2).equals("\\'")) ...
line.substring(i,i+1) only contains one character, and the for loop can replaced by line.indexOf("\\'") >= 0:
if (line.indexOf() >= 0) {
System.out.println("we found it " + line);
}
\\ is an escaped \ in Java, so I think your match string should be "\\".
P.s. I'm not exactly sure what you are trying to achieve here, but there appears to be more elegant, more "java-like" ways to do it than what you have here...

Replace string containing " with \"?

How can I replace string containing " with \" ?
replace(""","\"") is not working for me.
public static String replaceSpecialCharsForJson(String str){
return str.replace("'","\'")
.replace(":","\\:")
.replace("\"","\"")
.replace("\r", "\\r")
.replace("\n", "\\n");
}
You can try with:
replace("\"","\\\"")
Since both " and \ are metacharacters, you have to escape them with \
Try this one:
replace("\"","\\\"");
Every slash as part of a string needs to be escaped. So if you want a string to look like "\\", your code will have to contain String s = "\\\\". Ugly but true.
The same goes for any other special character that might be interpreted. Quotes and colons inclusive.
This means " \ " " will look like " \\ \" " (Added spaces to make separate escapes more visible)
Use:
str.replace("\"","\\\"")
So you escape the backslash.
You want to
replace " (properly escaped: \")
with \" (properly escaped: \\\").
The right call is:
replace("\"", "\\\"");
I tried this way. I don't know how much this helpful in your scenario
String oldStr = String.valueOf('"');
String newStr = File.separator.concat(String.valueOf('"'));
System.out.println(oldStr.replace(String.valueOf('"'),newStr));

Splitting on comma outside quotes

My program reads a line from a file. This line contains comma-separated text like:
123,test,444,"don't split, this",more test,1
I would like the result of a split to be this:
123
test
444
"don't split, this"
more test
1
If I use the String.split(","), I would get this:
123
test
444
"don't split
this"
more test
1
In other words: The comma in the substring "don't split, this" is not a separator. How to deal with this?
You can try out this regex:
str.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
This splits the string on , that is followed by an even number of double quotes. In other words, it splits on comma outside the double quotes. This will work provided you have balanced quotes in your string.
Explanation:
, // Split on comma
(?= // Followed by
(?: // Start a non-capture group
[^"]* // 0 or more non-quote characters
" // 1 quote
[^"]* // 0 or more non-quote characters
" // 1 quote
)* // 0 or more repetition of non-capture group (multiple of 2 quotes will be even)
[^"]* // Finally 0 or more non-quotes
$ // Till the end (This is necessary, else every comma will satisfy the condition)
)
You can even type like this in your code, using (?x) modifier with your regex. The modifier ignores any whitespaces in your regex, so it's becomes more easy to read a regex broken into multiple lines like so:
String[] arr = str.split("(?x) " +
", " + // Split on comma
"(?= " + // Followed by
" (?: " + // Start a non-capture group
" [^\"]* " + // 0 or more non-quote characters
" \" " + // 1 quote
" [^\"]* " + // 0 or more non-quote characters
" \" " + // 1 quote
" )* " + // 0 or more repetition of non-capture group (multiple of 2 quotes will be even)
" [^\"]* " + // Finally 0 or more non-quotes
" $ " + // Till the end (This is necessary, else every comma will satisfy the condition)
") " // End look-ahead
);
Why Split when you can Match?
Resurrecting this question because for some reason, the easy solution wasn't mentioned. Here is our beautifully compact regex:
"[^"]*"|[^,]+
This will match all the desired fragments (see demo).
Explanation
With "[^"]*", we match complete "double-quoted strings"
or |
we match [^,]+ any characters that are not a comma.
A possible refinement is to improve the string side of the alternation to allow the quoted strings to include escaped quotes.
Building upon #zx81's answer, cause matching idea is really nice, I've added Java 9 results call, which returns a Stream. Since OP wanted to use split, I've collected to String[], as split does.
Caution if you have spaces after your comma-separators (a, b, "c,d"). Then you need to change the pattern.
Jshell demo
$ jshell
-> String so = "123,test,444,\"don't split, this\",more test,1";
| Added variable so of type String with initial value "123,test,444,"don't split, this",more test,1"
-> Pattern.compile("\"[^\"]*\"|[^,]+").matcher(so).results();
| Expression value is: java.util.stream.ReferencePipeline$Head#2038ae61
| assigned to temporary variable $68 of type java.util.stream.Stream<MatchResult>
-> $68.map(MatchResult::group).toArray(String[]::new);
| Expression value is: [Ljava.lang.String;#6b09bb57
| assigned to temporary variable $69 of type String[]
-> Arrays.stream($69).forEach(System.out::println);
123
test
444
"don't split, this"
more test
1
Code
String so = "123,test,444,\"don't split, this\",more test,1";
Pattern.compile("\"[^\"]*\"|[^,]+")
.matcher(so)
.results()
.map(MatchResult::group)
.toArray(String[]::new);
Explanation
Regex [^"] matches: a quote, anything but a quote, a quote.
Regex [^"]* matches: a quote, anything but a quote 0 (or more) times , a quote.
That regex needs to go first to "win", otherwise matching anything but a comma 1 or more times - that is: [^,]+ - would "win".
results() requires Java 9 or higher.
It returns Stream<MatchResult>, which I map using group() call and collect to array of Strings. Parameterless toArray() call would return Object[].
You can do this very easily without complex regular expression:
Split on the character ". You get a list of Strings
Process each string in the list: Split every string that is on an even position in the List (starting indexing with zero) on "," (you get a list inside a list), leave every odd positioned string alone (directly putting it in a list inside the list).
Join the list of lists, so you get only a list.
If you want to handle quoting of '"', you have to adapt the algorithm a little bit (joining some parts, you have incorrectly split of, or changing splitting to simple regexp), but the basic structure stays.
So basically it is something like this:
public class SplitTest {
public static void main(String[] args) {
final String splitMe="123,test,444,\"don't split, this\",more test,1";
final String[] splitByQuote=splitMe.split("\"");
final String[][] splitByComma=new String[splitByQuote.length][];
for(int i=0;i<splitByQuote.length;i++) {
String part=splitByQuote[i];
if (i % 2 == 0){
splitByComma[i]=part.split(",");
}else{
splitByComma[i]=new String[1];
splitByComma[i][0]=part;
}
}
for (String parts[] : splitByComma) {
for (String part : parts) {
System.out.println(part);
}
}
}
}
This will be much cleaner with lambdas, promised!
Please see the below code snippet. This code only considers happy flow. Change the according to your requirement
public static String[] splitWithEscape(final String str, char split,
char escapeCharacter) {
final List<String> list = new LinkedList<String>();
char[] cArr = str.toCharArray();
boolean isEscape = false;
StringBuilder sb = new StringBuilder();
for (char c : cArr) {
if (isEscape && c != escapeCharacter) {
sb.append(c);
} else if (c != split && c != escapeCharacter) {
sb.append(c);
} else if (c == escapeCharacter) {
if (!isEscape) {
isEscape = true;
if (sb.length() > 0) {
list.add(sb.toString());
sb = new StringBuilder();
}
} else {
isEscape = false;
}
} else if (c == split) {
list.add(sb.toString());
sb = new StringBuilder();
}
}
if (sb.length() > 0) {
list.add(sb.toString());
}
String[] strArr = new String[list.size()];
return list.toArray(strArr);
}

Split string by array of characters

i want to split a string by array of characters,
so i have this code:
String target = "hello,any|body here?";
char[] delim = {'|',',',' '};
String regex = "(" + new String(delim).replaceAll("(.)", "\\\\$1|").replaceAll("\\|$", ")");
String[] result = target.split(regex);
everything works fine except when i want to add a character like 'Q' to delim[] array,
it throws exception :
java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence near index 11
(\ |\,|\||\Q)
so how can i fix that to work with non-special characters as well?
thanks in advance
how can i fix that to work with non-special characters as well
Put square brackets around your characters, instead of escaping them. Make sure that if ^ is included in your list of characters, you need to make sure it's not the first character, or escape it separately if it's the only character on the list.
Dashes also need special treatment - they need to go at the beginning or at the end of the regex.
String delimStr = String(delim);
String regex;
if (delimStr.equals("^") {
regex = "\\^"
} else if (delimStr.charAt(0) == '^') {
// This assumes that all characters are distinct.
// You may need a stricter check to make this work in general case.
regex = "[" + delimStr.charAt(1) + delimStr + "]";
} else {
regex = "[" + delimStr + "]";
}
Using Pattern.quote and putting it in square brackets seems to work:
String regex = "[" + Pattern.quote(new String(delim)) + "]";
Tested with possible problem characters.
Q is not a control character in a regex, so you do not have to put the \\ before it (it only serves to mark that you must interpret the following character as a literal, and not as a control character).
Example
`\\.` in a regex means "a dot"
`.` in a regex means "any character"
\\Q fails because Q is not special character in a regex, so it does not need to be quoted.
I would make delim a String array and add the quotes to these values that need it.
delim = {"\\|", ..... "Q"};

Regular expression to recognize string of '#'

I have a java question. I can't figure out how to write my regular expression to print something to a file when encountering one or more instances of '#'. It must not print when the string equals "", but it must print when the string equals "#". Here's my code:
int num = 1;
StringBuffer noletterbuf = new StringBuffer(nospaces);
noletterbuf.deleteCharAt(0);
String noletter = noletterbuf.toString();
//if(num == noletter.split("[^#]").length){//applies # to C# and C
if(num == noletter.split("[#*]").length){//applies # to C
double yacc = octave*-50;
p6.println("sb.append(\"/Times-Roman findfont 70 scalefont setfont 1 -1 scale newpath \"); sb.append(" + xaccplace + " + \" \" +" + yacc + " + \" moveto \"); sb.append(\"( # ) show 1 -1 scale \");");
}
Thanks in advance!
Bjorn
Why use regex and .split() at all, since you just discard the resulting array?
You can check if the string contains # using the following:
if (noletter.indexOf('#') >= 0) {
// ...
}
Your code:
noletter.split("[#*]")
This will split at each # and each *, since the asterisk is within brackets.
A simple way to check using regex is:
if (str.matches(".*#.*")) // true if there's a # in str
I don't understand the "no spaces" relevance, or why you used a StringBuffer, or why you deleted the first character.

Categories

Resources