Question about java String "hello" and 'hello' - java

Why this is invalid in java?
List<String> items=new ArrayList<String>();
items.add("hello"); // valid
items.add('hello'); // invalid (error: invalid character constants)

Because '' single quotes are used for char variables.
Meaning 'a', 'b', and so on. So only one character per variable.
The double quotes on the other side "" are used to initialize String variables, which are several characters gathered together into one variable e.g "i am a string"
char c = 'c' // I use single quotes because I am single :)
String str = "This is a string" // I use double quotes because I got a lot in me

Related

how to check for brackets outside two quotes in a String

i have for instance a String : if('{' == '{'){.
i would want it to not detect the brackets inside the ' '
but i do want it to detect the one at the end which is not inside the quotes
what the best way of doing i tried to loop through all chars but is there a quicker method?
You can simply remove those braces altogether or replace them with something meaningful. To just remove those '{' and '}' characters from the string then you could do it like this using the String#replaceAll() method which accepts a Regular Expression (regex), for example:
// Original String:
String strg1 = "if('{' == '{'){";
/* Apply change and place into a new string (strg2)
so to keep old string original (in strg1). */
String strg2 = strg1.replaceAll("'\\{'|'\\}'", "");
// Display the new String strg2:
System.out.println(strg2);
The Console Window will display:
if( == ){
The regex "'\\{'|'\\}'" used above basically does the following:
Replace All instances of '{' OR | All instances of '}' within the string with Null String "" (nothing). Within the Expression, the curly braces are escaped \\{ because they have special meaning within a Regular Expression and by escaping those characters informs regex processing that we mean literal character.
If you want to replace those '{' and '}' character combinations with something meaningful like specific values then you can replace those items separately, for example:
// Original String:
String strg1 = "if('{' == '}'){";
int value1 = 10; // An open brace ( '{' ) will be converted to this value
int value2 = 24; // A close brace ( '}' ) will be converted to this value
/* Apply change and place into a new string (strg2)
so to keep old string original (in strg1). */
String strg2 = strg1.replaceAll("'\\{'", String.valueOf(value1))
.replaceAll("'\\}'", String.valueOf(value2));
// Display the new String strg2:
System.out.println(strg2);
The console window will display:
if(10 == 24){
In the above code you will of noticed that the String#valueOf() method was used within the replacement section of the String#replaceAll() method. This is because the replacement values we want to use were declared as int data types and the replaceAll() method requires String as a replcement argument therefore we take those int values and convert them to String type.

How to split a string twice and add it to a linked list?

I tried to split a string and added it to a linked list. Each node in the linked list is a polynomial boundary. I tried this but it gave me a dangling meta character exception, what did I do wrong?
String s = "X^2+3x+5";
LinkedList p_list = new LinkedList();
s.toLowerCase();
s.replace("*x", "x");
s.replace("x^", "x");
s.replaceAll("--","+");
s.replaceAll("+-", "-");
s.replaceAll(" ", "");
String [] st = s.split("(?=[+-])");
String [] st2 = new String[2];
for(int i=0;i<=st.length;i++){
if(st[i].contains("x")){
st2=st[i].split("x");
if(st2[0].length()== 0 && st2[1].length()== 0){
p_list.addFirst(1,1);
}else if(st2[0].length()== 1 && st2[1].length()== 0){
p_list.addFirst(Integer.parseInt(st2[0]),0);
}
} else {
p_list.addFirst(Integer.parseInt(st2[0]),Integer.parseInt(st2[1]));
}
}
p_list.printList();
replace accepts a String, but replaceAll accepts a regex, and a regex that begins with + is invalid. You have two options:
escape the character +, in Java it's \\+
use Pattern#quote
Important note: String is immutable, you should assign the result to a new String.
The stack trace is pretty self-explanatory:
Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta
character '+' near index 0
+-
^
You need to escape the + symbol in the following line:
s = s.replaceAll("\\+-", "-"); // Note: you need to assign the result back to 's'
Not the answer (you already got 2 of them) but very important to note that String is immutable so the manipulation methods (e.g. toLowerCase, replace etc..) will produce a new string and will not modify the String object on which they are called so assign the result to your string in order for the changes to be in effect, i.e:
s = s.toLowerCase();
First of all String is immutable, so:
String s = "X^2+3x+5";
s.toLowerCase();
s.replaceAll(....)
s.substring(etc ...)
Will give you same String as declared at the beginning. The replaceAll() method takes a regex as the first parameter. And the "*" has special meaning in a regex. You will need to escape it with \.
String result = s.toLowerCase().replaceAll("\\*x", "x")
.replace("x^", "x").replaceAll("--", "+")
.replaceAll("\\+-", "-").replaceAll("\\+-", "-")
.replaceAll(" ", "");

Unclosed Character Literal error

Got the error "Unclosed Character Literal" , using BlueJ, when writing:
class abc
{
public static void main(String args[])
{
String y;
y = 'hello';
System.out.println(y);
}
}
But I can't figure out what is wrong.
Any idea?
Thanks.
In Java, single quotes can only take one character, with escape if necessary. You need to use full quotation marks as follows for strings:
y = "hello";
You also used
System.out.println(g);
which I assume should be
System.out.println(y);
Note: When making char values (you'll likely use them later) you need single quotes. For example:
char foo='m';
Java uses double quotes for "String" and single quotes for 'C'haracters.
I'd like to give a small addition to the existing answers.
You get the same "Unclosed Character Literal error", if you give value to a char with incorrect unicode form.
Like when you write:
char HI = '\3072';
You have to use the correct form which is:
char HI = '\u3072';
'' encloses single char, while "" encloses a String.
Change
y = 'hello';
-->
y = "hello";
String y = "hello";
would work (note the double quotes).
char y = 'h';
this will work for chars (note the single quotes)
but the type is the key: '' (single quotes) for one char, "" (double quotes) for string.
There are 8 primitive datatypes in Java.
char is one of them. When compiler sees a char datatype is defined. It allocates 1 Bytes of memory from JVM heap and expects a value after = symbol with two conditions.
value enclosed inside ' (single quotes).
value to be single character long. It can be either a single character or valid code corresponding single character, which you can't type using English Keyboard.
In the same way, a datatype of String type should be enclosed with "(double quotes) and can have any length characters sequence.
In the given example you have mixed concepts of both char and String datatype. the compiler clearly saying:
Unclosed Character Literal
Means, you started with ' single quote, so compiler just expects a single character after opening ' and then a closing '. Hence, the character literal is considered unclosed and you see the error.
So, either you use char data type and ' single quotes to enclose single character.
Or use String datatype and " double quotes to enclose any length of character sequence.
So, correct way is:
String y = "hello";
System.out.println(y);
Use double quotes symbol as I mention below
Your y data type is String, and it should double quotes symbol
class abc
{
public static void main(String args[])
{
String y;
y = "hello";
System.out.println(y);
}
}
Character only takes one value dude! like:
char y = 'h';
and maybe you typed like char y = 'hello'; or smthg. good luck. for the question asked above the answer is pretty simple u have to use DOUBLE QUOTES to give a string value. easy enough;)

string split to string array

I have a string variable Result that contains a string like:
"<field1>text</field1><field2>text</field2> etc.."
I use this code to try to split it:
Result = Result.replace("><", ">|<");
String[] Fields = Result.split("|");
According to the many websites, including this one, this should give me an array like this:
Fields[0] = "<field1>text</field2>"
Fields[1] = "<field2>test</field2>"
etc...
But it gives me an array like:
Fields(0) = ""
Fields(1) = "<"
Fields(2) = "f"
Fields(3) = "i"
Fields(4) = "e"
etc..
So, what am I doing wrong?
Your call to split("|") is parsing | as a regular-expression-or, which on its own will split between every character.
You can regex-escape the character to prevent this from occurring, or use a different temporary split character altogether.
String[] fields = result.split("\\|");
or
result = result.replace("><", ">~<");
String[] fields = result.split("~");
Try doing
String[] fields = result.split("\\|");
Note that I've used more conventional variable names (they shouldn't start with capital letters).
Remember that the split methods takes a regular expression as an argument, and | has a specific meaning in the world of regular expressions, which is why you're not receiving what you were expecting.
Relevant documentation:
split

Writing a regex in java. Using the string.split() method. I want it to stop splitting after the first occurrence of '('

I have strings with this format: "a,b, c,d" and this format: "a(b,c,d)"
I want to split on ',' or ', ' but I want to terminate splitting when I encounter the '(' in the second format.
This is what I had before I started hacking.
String [] stringArray = string.split(", |,");
The array of the first format would contain: 'a', 'b', 'c', 'd'
The array of the second format would conaint 'a(b,c,d)'
Example:
String string1 = "ab,cd, de";
String string2 = "ab(de,ef);
String [] array1 = string1.split(...);
String [] array2 = string2.split(...);
array1 result: ["ab" "cd" "de"]
array2 result: ["ab(de,ef)"]
The number of characters between the commas are not limited. I hope this is more clear.
Thanks.
If you know the parentheses are always properly balanced and they'll never be nested inside other parens, this will work:
String[] result = source.split(",\\s*(?![^()]*\\))");
If the lookahead finds a ) without seeing a ( first, it must be inside a pair of parens. Given this string:
"ab,cd, de,ef(gh,ij), kl,mn"
...result will be:
["ab", "cd", "de", "ef(gh,ij)", "kl", "mn"]
I think what you could need is a negative lookbehind; according to the doc, Java regex are like (more or less) Perl regex; but variable length lookbehind is not implemented in Perl, so that (?<!\(.*),\s* won't work (it would match comma followed by any number of spaces or no space, and not preceded by a ( followed by anything, i.e. would match comma only if not preceded by a ().
I believe the easiest thing is to split on the first ( occurrence (you can avoid regex to do so) and treat the two resulting segments differently, splitting the first on , and adding to the final array the second (prepended with the maybe lost ().
EDIT
since "a(b,d)" should give "a(b,d)", you must append whatever comes after ( (included) to the last splited string from the "first" segment. However, the concept is as written before.
Use the indexOf() method.
Initially, check if a string has a "(".
index = string.indexOf('(');
if(index ==-1) // it means there is no '('
{
string.split(...);
}
else
{
subString = string.subString(0,index); // the part of the string before the '('
// now do the following-
// 1. proceed with split on substring
// array1 = substring.split(...)
// 2. Create a new array, insert the elements of array1 in it,
// followed by the remaining part of the string
// array2 = combine(array1, string.subString(index+1)); // <-- you will need to write this method
}

Categories

Resources