I want to compare two strings using Java. First sting name i get from .mif file using GDAL in cp1251 encoding. Second kadname i get from jsp. To compare i do this:
if (attrValue instanceof String)
{
String string3 =
new String((attrValue.toString()).getBytes("ISO-8859-1"), "cp1251");
dbFeature.setAttribute(name, string3);
System.out.println("Name=" + name);
System.out.println("kadname=" + kadname);
if (name.equalsIgnoreCase(kadname))
{
kadnum = string3;
System.out.println("string3" + string3);
}
}
And in console i get this:
Name = kadnumm
kadname = kadnumm
Whats wrong with this?
The only reason I can see for them not being equal is the leading or trailing whitespace.
You can trim the string to remove any of those whitespaces, and then compare them: -
if (name.trim().equalsIgnoreCase(kadname.trim()))
Or, there might be some other non-printable characters, which won't get removed by trimming. You can try printing your strings in single quotes, and check whether there are any: -
System.out.println("'" + name + "'");
Related
I have a string where it contains different combinations of the slashes
{"result":"{\"cov_details\":[{\"issue_date\":\"UNIT
OFFICE,NEYVELI\",\"cov\":\"MCWG\"}],\"dl_number\":\"TN31Y200000784\",\"address\":\"PERIYA COLONY KO
PAVAZHANGUDI VIRUDHACHALAM TK\",\"issue_date\":\"24-03-2010\",\"dob\":\"21-03-
1981\",\"name\":\"VICNESWARAN S\",\"blood_group\":\"\",\"validity\":{\"transport\":\"\",\"non-
transport\":\"4-01-2010 to 23-03-2040\"},\"father\\\/husband\":\"SELVAM\"}","status-
code":"101","request_id":"a2642ae9-2f10-4e9a-9f7e-c3ee1a9a2dbe"}
I want to replace all occurances of a single "" alone but ignore when "" is followed by "/" ( check out the father\\\/husband\ parameter. It should read father\/husband. How can I achieve this in Java?
Just hide "\/" by replacing it with another character sequence like "~~~", then restore it after:
String string = "father\\\\\\/husband\\";
System.out.println("Before\t:\t" + string);
System.out.println
(
"After\t:\t" + string
.replaceAll("\\\\/", "~~~")
.replaceAll("\\\\", "")
.replaceAll("~~~", "\\\\/")
);
Output:
Before : father\\\/husband\
After : father\/husband
public String replaceAll​(String regex, String replacement) accepts regex as the first parameter:
https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/lang/String.html#replaceAll(java.lang.String,java.lang.String)
Fill free to specify any pattern you need:
https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/util/regex/Pattern.html#sum
My String input is String Number = "546+90".
I want to give output like this "546 + 90".how can i do it in java? Right now I am trying:
Number.replaceAll("[0-9]"," ");
But it doesn't seem to be working. Does anyone have any suggestions?
Strings are immutable so you need to get the string resultant of the replace method:
public static void main(String[] args) {
String number="546+90";
number = number.replaceAll("\\+" , " + ");
System.out.println(number);
}
First, Number is a built-in class in the java.lang package, so you should never use that name.
Second, variables should be written in lower-case, so it should be number.
Third, Strings are immutable, so the need to get the return value from replaceAll().
If you want this string: "String Number=546+90"
to become this string: "546 + 90"
then you need to strip anything before = and add spaces around the +.
This can be done by chaining replace calls:
String number = "String Number=546+90";
number = number.replaceFirst(".*=", "")
.replaceAll("\\+", " + ");
System.out.println(number);
If you want other operators too, use a character class. You have to capture the character to retain it in the replacement string, and you must put - first or last (or escape it).
number = number.replaceFirst(".*=", "")
.replaceAll("([-+*/%])", " $1 ");
Adding an escape characters will solve your problem
String Number = "\"" + "546+90" + "\"";
I have a string
"#72c02c, #3498db, #e67e22, #9c8061, #4765a0, #79d5b3"
I want to convert it to the following:
"'#72c02c', '#3498db', '#e67e22', '#9c8061', '#4765a0', '#79d5b3'"
Is there any way to do so?
I don't know why everyone is using regex... this needs only a simple text replace:
str = "'" + str.replace(", ", "', '") + "'";
This just puts quotes before/after commas and puts a quote at each end, which is easy to understand.
String s = "#72c02c, #3498db, #e67e22, #e74c3c, #ecf0f1, #9b6bcc, #27d7e7, #9c8061, #4765a0, #79d5b3";
s = s.replaceAll("(#|,)","'$1");
if (s.charAt(s.length()-1) != ',')
s = s + "'";
Might not be the most elegant solution, but it handles the case of the final item in the string not ending with a ,. Will work if it does happen to end in a comma too.
If you are able to operate with it as with the simple String object instance, the you can do it with regex ([#\w]+) and String.replaceAll() method, like:
String testString = "#72c02c, #3498db, #e67e22, #e74c3c, #ecf0f1, #9b6bcc, #27d7e7, #9c8061, #4765a0, #79d5b3";
System.out.println(testString.replaceAll("([#\\w]+)","'$1'"));
Where with ([#\w]+), you just take every group of alpha-numeric characters or #
Then you just replace it with '$1', where $1 is the whole group, which was found.
I'm reading line by line from a text file which contains a string followed by a white space followed by another string. It's the second string I want to use for my method.
Example of text file:
0h e3ne6t
ie 51b0x
6 8qlaqi
ty2 9j5dbb
nwz55 7lrwor
So I want 'e3ne6t', then '51b0x' etc.
I've tried using the .substring method and have tried using " " and "\s" as representations of white space.
Here's a snippet of code that should give you a good idea of what I'm trying to achieve.
while ((strLine = br.readLine()) != null) {
lineNumber++;
System.out.println("lineNumber = " + lineNumber);
int index = strLine.indexOf(" "); // tried \\s
System.out.println("index = " + index);
strLine.substring(index);
System.out.println(strLine);
if (myString.equals(strLine)) {
System.out.println("Match Found!");;
System.out.println("myString = " + myString );
System.out.println("strLine =" + strLine);
}
}
I even tried changing the white space to a "+" but it still wouldn't work.
Suggestions?
substring doesn't change the contents of the string you call it on - nothing does, as String is immutable in Java. Instead, it returns a new string which is the relevant substring. So you can use:
strLine = strLine.substring(index);
(The same is true for things like toUpperCase, trim, replace etc.)
String's are immutable in java. you need to reassign the value retrieved by substring to the actual variable.
strLine=strLine.substring(index);
Also note that indexOf(str) doesn't take regex, so indexOf("\\s") would give you nothing.
As others have mentioned, Strings are immutable in Java. The substring method returns a new String that is the substring. But if you pass index to substring, then you will get a substring starting with your space character, e.g. " e3ne6t". So I would use this:
strLine = strLine.substring(index + 1);
to get your second field, advancing past the space character, as long as index is not -1 (not found).
Manipulating a String using .substring in Java
www.gleegrid.com/all_in_one/language/substring
For example I'm extracting a text String from a text file and I need those words to form an array. However, when I do all that some words end with comma (,) or a full stop (.) or even have brackets attached to them (which is all perfectly normal).
What I want to do is to get rid of those characters. I've been trying to do that using those predefined String methods in Java but I just can't get around it.
Reassign the variable to a substring:
s = s.substring(0, s.length() - 1)
Also an alternative way of solving your problem: you might also want to consider using a StringTokenizer to read the file and set the delimiters to be the characters you don't want to be part of words.
Use:
String str = "whatever";
str = str.replaceAll("[,.]", "");
replaceAll takes a regular expression. This:
[,.]
...looks for each comma and/or period.
To remove the last character do as Mark Byers said
s = s.substring(0, s.length() - 1);
Additionally, another way to remove the characters you don't want would be to use the .replace(oldCharacter, newCharacter) method.
as in:
s = s.replace(",","");
and
s = s.replace(".","");
You can't modify a String in Java. They are immutable. All you can do is create a new string that is substring of the old string, minus the last character.
In some cases a StringBuffer might help you instead.
The best method is what Mark Byers explains:
s = s.substring(0, s.length() - 1)
For example, if we want to replace \ to space " " with ReplaceAll, it doesn't work fine
String.replaceAll("\\", "");
or
String.replaceAll("\\$", ""); //if it is a path
Note that the word boundaries also depend on the Locale. I think the best way to do it using standard java.text.BreakIterator. Here is an example from the java.sun.com tutorial.
import java.text.BreakIterator;
import java.util.Locale;
public static void main(String[] args) {
String text = "\n" +
"\n" +
"For example I'm extracting a text String from a text file and I need those words to form an array. However, when I do all that some words end with comma (,) or a full stop (.) or even have brackets attached to them (which is all perfectly normal).\n" +
"\n" +
"What I want to do is to get rid of those characters. I've been trying to do that using those predefined String methods in Java but I just can't get around it.\n" +
"\n" +
"Every help appreciated. Thanx";
BreakIterator wordIterator = BreakIterator.getWordInstance(Locale.getDefault());
extractWords(text, wordIterator);
}
static void extractWords(String target, BreakIterator wordIterator) {
wordIterator.setText(target);
int start = wordIterator.first();
int end = wordIterator.next();
while (end != BreakIterator.DONE) {
String word = target.substring(start, end);
if (Character.isLetterOrDigit(word.charAt(0))) {
System.out.println(word);
}
start = end;
end = wordIterator.next();
}
}
Source: http://java.sun.com/docs/books/tutorial/i18n/text/word.html
You can use replaceAll() method :
String.replaceAll(",", "");
String.replaceAll("\\.", "");
String.replaceAll("\\(", "");
etc..