Java String output - java

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" + "\"";

Related

Regular expression for string with apostrophes

I'm trying to build regex which will filter form string all non-alphabetical characters, and if any string contains single quotes then I want to keep it as an exception to the rule.
So for example when I enter
car's34
as a result I want to get
car's
when I enter
*&* Lisa's car 0)*
I want to get
Lisa's
at the moment I use this:
string.replaceAll("[^A-Za-z]", "")
however, it gives me only alphabets, and removed the desired single quotas.
This will also remove apostrophes that are not "part if words":
string = string.replaceAll("[^A-Za-z' ]+|(?<=^|\\W)'|'(?=\\W|$)", "")
.replaceAll(" +", " ").trim();
This first simply adds an apostrophe to the list of chars you want to keep, but uses look arounds to find apostrophes not within words, so
I'm a ' 123 & 'test'
would become
I'm a test
Note how the solitary apostrophe was removed, as well as the apostrophes wrapping test, but I'm was preserved.
The subsequent replaceAll() is to replace multiple spaces with a single space, which will result if there's a solitary apostrophe in the input. A further call to trim() was added in case it occurs at the end of the input.
Here's a test:
String string = "I'm a ' 123 & 'test'";
string = string.replaceAll("[^A-Za-z' ]+|(?<=^|\\W)'|'(?=\\W|$)", "").replaceAll(" +", " ").trim();
System.out.println(string);
Output:
I'm a test
Isn't this working ?
[^A-Za-z']
The obvious solution would be:
string.replaceAll("[^A-Za-z']", "")
I suspect you want something more.
You can try the regular expression:
[^\p{L}' ]
\p{L} denote the category of Unicode letters.
In ahother hand, you need to use a constant of Pattern for avoid recompiled the expression every time, something like that:
private static final Pattern REGEX_PATTERN =
Pattern.compile("[^\\p{L}' ]");
public static void main(String[] args) {
String input = "*&* Lisa's car 0)*";
System.out.println(
REGEX_PATTERN.matcher(input).replaceAll("")
); // prints " Lisa's car "
}
#Bohemian has a good idea but word boundaries are called for instead of lookaround:
string.replaceAll("([^A-Za-z']|\B'|'\B)+", " ");

String.split() at a meta character +

I'm making a simple program that will deal with equations from a String input of the equation
When I run it, however, I get an exception because of trying to replace the " +" with a " +" so i can split the string at the spaces. How should I go about using
the string replaceAll method to replace these special characters? Below is my code
Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0
+
^
public static void parse(String x){
String z = "x^2+2=2x-1";
String[] lrside = z.split("=",4);
System.out.println("Left side: " + lrside[0] + " / Right Side: " + lrside[1]);
String rightside = lrside[0];
String leftside = lrside[1];
rightside.replaceAll("-", " -");
rightside.replaceAll("+", " +");
leftside.replaceAll("-", " -"); leftside.replaceAll("+", " +");
List<String> rightt = Arrays.asList(rightside.split(" "));
List<String> leftt = Arrays.asList(leftside.split(" "));
System.out.println(leftt);
System.out.println(rightt);
replaceAll accepts a regular expression as its first argument.
+ is a special character which denotes a quantifier meaning one or more occurrences. Therefore it should be escaped to specify the literal character +:
rightside = rightside.replaceAll("\\+", " +");
(Strings are immutable so it is necessary to assign the variable to the result of replaceAll);
An alternative to this is to use a character class which removes the metacharacter status:
rightside = rightside.replaceAll("[+]", " +");
The simplest solution though would be to use the replace method which uses non-regex String literals:
rightside = rightside.replace("+", " +");
I had similar problem with regex = "?". It happens for all special characters that have some meaning in a regex. So you need to have "\\" as a prefix to your regex.
rightside = rightside.replaceAll("\\+", " +");
String#replaceAll expects regex as input, and + is not proper pattern, \\+ would be pattern. rightside.replaceAll("\\+", " +");
The reason behind this is - There are reserved characters for regex. So when you split them using the java split() method, You will have to use them with escape.
FOr example you want to split by + or * or dot(.) then you will have to do it as split("\+") or split("\*") or split("\.") according to your need.
The reason behind my long explanation on regex is -
YOU MAY FACE IT in OTHER PLACES TOO.
For example the same issue will occur if you use replace or replaceAll methods of java Because they are also working based on regex.

Manipulating a String using .substring in Java

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

String comparison in Java

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 + "'");

How do I delete specific characters from a particular String in Java?

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..

Categories