How to split this string in java? - java

I have this code
lStock.setText(" Put " + getLoc(i));
At the moment it prints out like this on the GUI:
3I031C
what I want to show now on the screen GUI is:
3I03-1C
I tried testing the split() but I'm confused.

String.split is used to break apart a string based on some particular delimiter. You don't have a delimiter here.
If you always want to break after the fourth character:
String str = "3I031C";
String out = str.substring(0, 4) + '-' + str.substring(4);

You can't use the split method since it needs a delimiter, but you're string doesn't contain any.
You can try using substring:
str = str.substring(0, 4) + "-" + str.substring(4);
But this will only work if the string always have the same length and format.

If its a fixed output try like below
s = s.substring(0, 4) + "-" + s.substring(4);
refer to String.substring()

Related

String format Java

I would like to do the following thing:
I have a String in Java, for instance
"4231354"
My aim is to show a version number in this way
XXX-X-X.XX
which means than I need to use a function to show
"423-1-3.54"
Thanks.
You can try this too:
StringBuilder str = new StringBuilder("4235167");
str.insert(3, '-');
str.insert(5, '-');
str.insert(7, '.');
System.out.println(str);
You can do it with replaceAll, like this:
String ver = "4231354";
String fmt = ver.replaceAll("(\\d{3})(\\d)(\\d)(\\d{2})", "$1-$2-$3.$4");
Regular expression defined by the first parameter has four groups - a group of three characters, two groups of single characters, and a group of two characters. The second parameter uses these groups, which are numbered $1 through $4, to produce the formatting that you are looking to achieve.
Demo.
I like the old way
As you mentioned length is fixed so you can use substring
String st="4231354";
String newString=st.substring(0,3)+"-"+st.substring(3,4)+"-"+st.substring(4,5)+"."+st.substring(5,st.length());
System.out.println(newString);
DEMO
If you want to get
"423-1-3.54"
All you have to do is:
String originalNumber = "4231354";
String versionNumber = new String(originalNumber.substring(0, 3) + "-" + originalNumber.substring(3, 4) + "-" + originalNumber.substring(4, 5) + "." + originalNumber.substring(5));
Or use String.format()
public Format(String version) {
String v = String.format("%s-%s-%s.%s",
version.substring(0,3),
version.substring(3,4),
version.substring(4,5),
version.substring(5,7));
System.out.println(v);
}

How to remove unknown characters from a string which follows a particular format?

I have a String in this format: &?0907141|somename|5009-07-2014|sample
All I want to do is to remove 50 from the above String format, but the number might be anything not just 50, I cannot go by index position since the text "somename" might be changed to something else, but String will always be in the same format as above.
How do I remove it in the easiest possible way?
This will remove two characters after the second pipe.
String s = "&?0907141|somename|5009-07-2014|sample";
System.out.println(s.replaceFirst("(.*\\|.*\\|)..(.*\\|.*)", "$1$2"));
try this
String.replaceAll ("\\|[0-9]{2}", "|");
it will replace a pipe and 2 digits with a pipe
1. String[] arr= `String#split()` on `|`
2. use replace() / regex etc on arr[2].
3. Code..
String s = "&?0907141|somename|5009-07-2014|sample";
String splits[] = s.split("\\|");
s = splits[0] + "|" + splits[1] + "|" + splits[2].substring(2) + "|" + splits[3];

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.

How to remove newlines from beginning and end of a string?

I have a string that contains some text followed by a blank line. What's the best way to keep the part with text, but remove the whitespace newline from the end?
Use String.trim() method to get rid of whitespaces (spaces, new lines etc.) from the beginning and end of the string.
String trimmedString = myString.trim();
String.replaceAll("[\n\r]", "");
This Java code does exactly what is asked in the title of the question, that is "remove newlines from beginning and end of a string-java":
String.replaceAll("^[\n\r]", "").replaceAll("[\n\r]$", "")
Remove newlines only from the end of the line:
String.replaceAll("[\n\r]$", "")
Remove newlines only from the beginning of the line:
String.replaceAll("^[\n\r]", "")
tl;dr
String cleanString = dirtyString.strip() ; // Call new `String::string` method.
String::strip…
The old String::trim method has a strange definition of whitespace.
As discussed here, Java 11 adds new strip… methods to the String class. These use a more Unicode-savvy definition of whitespace. See the rules of this definition in the class JavaDoc for Character::isWhitespace.
Example code.
String input = " some Thing ";
System.out.println("before->>"+input+"<<-");
input = input.strip();
System.out.println("after->>"+input+"<<-");
Or you can strip just the leading or just the trailing whitespace.
You do not mention exactly what code point(s) make up your newlines. I imagine your newline is likely included in this list of code points targeted by strip:
It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space ('\u00A0', '\u2007', '\u202F').
It is '\t', U+0009 HORIZONTAL TABULATION.
It is '\n', U+000A LINE FEED.
It is '\u000B', U+000B VERTICAL TABULATION.
It is '\f', U+000C FORM FEED.
It is '\r', U+000D CARRIAGE RETURN.
It is '\u001C', U+001C FILE SEPARATOR.
It is '\u001D', U+001D GROUP SEPARATOR.
It is '\u001E', U+001E RECORD SEPARATOR.
It is '\u001F', U+0
If your string is potentially null, consider using StringUtils.trim() - the null-safe version of String.trim().
If you only want to remove line breaks (not spaces, tabs) at the beginning and end of a String (not inbetween), then you can use this approach:
Use a regular expressions to remove carriage returns (\\r) and line feeds (\\n) from the beginning (^) and ending ($) of a string:
s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "")
Complete Example:
public class RemoveLineBreaks {
public static void main(String[] args) {
var s = "\nHello world\nHello everyone\n";
System.out.println("before: >"+s+"<");
s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "");
System.out.println("after: >"+s+"<");
}
}
It outputs:
before: >
Hello world
Hello everyone
<
after: >Hello world
Hello everyone<
I'm going to add an answer to this as well because, while I had the same question, the provided answer did not suffice. Given some thought, I realized that this can be done very easily with a regular expression.
To remove newlines from the beginning:
// Trim left
String[] a = "\n\nfrom the beginning\n\n".split("^\\n+", 2);
System.out.println("-" + (a.length > 1 ? a[1] : a[0]) + "-");
and end of a string:
// Trim right
String z = "\n\nfrom the end\n\n";
System.out.println("-" + z.split("\\n+$", 2)[0] + "-");
I'm certain that this is not the most performance efficient way of trimming a string. But it does appear to be the cleanest and simplest way to inline such an operation.
Note that the same method can be done to trim any variation and combination of characters from either end as it's a simple regex.
Try this
function replaceNewLine(str) {
return str.replace(/[\n\r]/g, "");
}
String trimStartEnd = "\n TestString1 linebreak1\nlinebreak2\nlinebreak3\n TestString2 \n";
System.out.println("Original String : [" + trimStartEnd + "]");
System.out.println("-----------------------------");
System.out.println("Result String : [" + trimStartEnd.replaceAll("^(\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029])|(\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029])$", "") + "]");
Start of a string = ^ ,
End of a string = $ ,
regex combination = | ,
Linebreak = \r\n|[\n\x0B\x0C\r\u0085\u2028\u2029]
Another elegant solution.
String myString = "\nLogbasex\n";
myString = org.apache.commons.lang3.StringUtils.strip(myString, "\n");
For anyone else looking for answer to the question when dealing with different linebreaks:
string.replaceAll("(\n|\r|\r\n)$", ""); // Java 7
string.replaceAll("\\R$", ""); // Java 8
This should remove exactly the last line break and preserve all other whitespace from string and work with Unix (\n), Windows (\r\n) and old Mac (\r) line breaks: https://stackoverflow.com/a/20056634, https://stackoverflow.com/a/49791415. "\\R" is matcher introduced in Java 8 in Pattern class: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html
This passes these tests:
// Windows:
value = "\r\n test \r\n value \r\n";
assertEquals("\r\n test \r\n value ", value.replaceAll("\\R$", ""));
// Unix:
value = "\n test \n value \n";
assertEquals("\n test \n value ", value.replaceAll("\\R$", ""));
// Old Mac:
value = "\r test \r value \r";
assertEquals("\r test \r value ", value.replaceAll("\\R$", ""));
String text = readFileAsString("textfile.txt");
text = text.replace("\n", "").replace("\r", "");

How to replace the last word in a string

Does anyone knows how to replace the last word in a String.
Currently I am doing:
someStr = someStr.replace(someStr.substring(someStr.lastIndexOf(" ") + 1), "New Word");
The above code replaces every single occurance of the word in the string.
Thanks.
You could create a new string "from scratch" like this:
someStr = someStr.substring(0, someStr.lastIndexOf(" ")) + " New Word";
Another option (if you really want to use "replace" :) is to do
someStr = someStr.replaceAll(" \\S*$", " New Word");
replaceAll uses regular expressions and \S*$ means a space, followed by some non-space characters, followed by end of string. (That is, replace the characters after the last space.)
You're not far from the solution. Just keep the original string until the last index of " ", and append the new word to this substring. No need for replace here.
What your code is doing is replacing the substring by "New word".
Instead you need to substring first, and then do a replace on that string.
Here's how I would do it
someStr = someStr.substring(0, someStr.lastIndexOf(" ") + 1) + "New word"
try:
someStr = someStr.substring( someStr.lastIndexOf(" ") ) + " " + new_word;
use this: someStr.substring(0, someStr.lastIndexOf(" ")) + "New Word".
You can also use regular expression, e.g. someStr.repalaceFirst("\s+\S+$", " " + "New Word")
Try this regex (^.+)b(.+$)
Example (Replace the last b character)
System.out.println("1abchhhabcjjjabc".replaceFirst("(^.+)b(.+$)", "$1$2"));

Categories