Replacing last character in a String with java - java

I have a string:
String fieldName = "A=2,B=3 and C=3,";
Now I want to replace last , with space.
I have used:
if (fieldName.endsWith(",")) {
fieldName.replace(",", " ");
fieldName = fieldName.replace((char) (fieldName.length() - 1), 'r');
}
System.out.println("fieldName = " + fieldName);
But still I am getting the same old string. How I can get this output instead?
fieldName = A=2,B=3 and C=3

You can simply use substring:
if(fieldName.endsWith(","))
{
fieldName = fieldName.substring(0,fieldName.length() - 1);
}
Make sure to reassign your field after performing substring as Strings are immutable in java

i want to replace last ',' with space
if (fieldName.endsWith(",")) {
fieldName = fieldName.substring(0, fieldName.length() - 1) + " ";
}
If you want to remove the trailing comma, simply get rid of the + " ".

To get the required result you can do following:
fieldName = fieldName.trim();
fieldName = fieldName.substring(0,fieldName.length() - 1);

fieldName = fieldName.substring(0, string.length()-1) + " ";

Firstly Strings are immutable in java, you have to assign the result of the replace to a variable.
fieldName = fieldName.replace("watever","");
You can use also use regex as an option using String#replaceAll(regex, str);
fieldName = fieldName.replaceAll(",$","");

Try this:
s = s.replaceAll("[,]$", "");

if (fieldName.endsWith(",")) {
fieldName = fieldName.substring(0, fieldName.length()-1) + " ";
}

StringBuilder replace method can be used to replace the last character.
StringBuilder.replace(startPosition, endPosition, newString)
StringBuilder builder = new StringBuilder(fieldName);
builder.replace(builder.length()-1, builder.length(), "");
builder.toString();

You can simply use :
if(fieldName.endsWith(","))
{
StringUtils.chop(fieldName);
}
from commons-lang

org.apache.commons.lang3.StringUtils.removeEnd() and org.springframework.util.StringUtils.trimTrailingCharacter() are your friends:
StringUtils.removeEnd(null, *) = null
StringUtils.removeEnd("", *) = ""
StringUtils.removeEnd(*, null) = *
StringUtils.removeEnd("www.domain.com", ".com.") = "www.domain.com"
StringUtils.removeEnd("www.domain.com", ".com") = "www.domain"
StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
StringUtils.removeEnd("abc", "") = "abc"
#Test
public void springStringUtils() {
String url = "https://some.site/path/";
String result = org.springframework.util.StringUtils.trimTrailingCharacter(url, '/');
assertThat(result, equalTo("https://some.site/path"));
}

you can use regular expressions to identify the last comma (,) and replace it with " " as follow:
if(fieldName.endsWith(","))
{
fieldName = fieldName.replace(/,([^,]*)$/," ");
}

Already #Abubakkar Rangara answered easy way to handle your problem
Alternative is :
String[] result = null;
if(fieldName.endsWith(",")) {
String[] result = fieldName.split(",");
for(int i = 1; i < result.length - 1; i++) {
result[0] = result[0].concat(result[i]);
}
}

Modify the code as fieldName = fieldName.replace("," , " ");

Related

How to remove text between brackets in multiple lines

I have a big text files and I want to remove everything that is between
double curly brackets.
So given the text below:
String text = "This is {{\n" +
"{{the multiline\n" +
"text}} file }}\n" +
"what I\n" +
"{{ to {{be\n" +
"changed}}\n" +
"}} want.";
String cleanedText = Pattern.compile("(?<=\\{\\{).*?\\}\\}", Pattern.DOTALL).matcher(text).replaceAll("");
System.out.println(cleanedText);
I want the output to be:
This is what I want.
I have googled around and tried many different things but I couldn't find anything close to my case and as soon as I change it a little bit everything gets worse.
Thanks in advance
You can use this :
public static void main(String[] args) {
String text = "This is {{\n" +
"{{the multiline\n" +
"text}} file }}\n" +
"what I\n" +
"{{ to {{be\n" +
"changed}}\n" +
"}} want.";
String cleanedText = text.replaceAll("\\n", "");
while (cleanedText.contains("{{") && cleanedText.contains("}}")) {
cleanedText = cleanedText.replaceAll("\\{\\{[a-zA-Z\\s]*\\}\\}", "");
}
System.out.println(cleanedText);
}
A regular expression cannot express arbitrarily nested structures; i.e. any syntax that requires a recursive grammar to describe.
If you want to solve this using Java Pattern, you need to do it by repeated pattern matching. Here is one solution:
String res = input;
while (true) {
String tmp = res.replaceAll("\\{\\{[^}]*\\}\\}", "");
if (tmp.equals(res)) {
break;
}
res = tmp;
}
This is not very efficient ...
That can be transformed into an equivalent, but more concise form:
String res = input;
String tmp;
while (!(tmp = res.replaceAll("\\{\\{[^}]*\\}\\}", "")).equals(res)) {
res = tmp;
}
... but I prefer the first version because it is (IMO) a lot more readable.
I am not an expert in regular expression, so I just write a loop which does this for you. If you don't have/want to use a regEx, then it could be helpful for you;)
public static void main(String args[]) {
String text = "This is {{\n" +
"{{the multiline\n" +
"text}} file }}\n" +
"what I\n" +
"{{ to {{be\n" +
"changed}}\n" +
"}} want.";
int openBrackets = 0;
String output = "";
char[] input = text.toCharArray();
for(int i=0;i<input.length;i++){
if(input[i] == '{'){
openBrackets++;
continue;
}
if(input[i] == '}'){
openBrackets--;
continue;
}
if(openBrackets==0){
output += input[i];
}
}
System.out.println(output);
}
My suggestion is to remove anything between curly brackets, starting at the innermost pair:
String text = "This is {{\n" +
"{{the multiline\n" +
"text}} file }}\n" +
"what I\n" +
"{{ to {{be\n" +
"changed}}\n" +
"}} want.";
Pattern p = Pattern.compile("\\{\\{[^{}]+?}}", Pattern.MULTILINE);
while (p.matcher(text).find()) {
text = p.matcher(text).replaceAll("");
}
resulting in the output
This is
what I
want.
This might fail when having single curly brackets or unpaired pair of brackets, but could be good enough for your case.

Java PatternSyntaxException when replacing characters in a String object

I am trying to create string of this list without the following character , [] as will I want to replace all two spaces after deleting them.
I have tried the following but I am geting the error in the title.
Simple:
[06:15, 06:45, 07:16, 07:46]
Result should look as this:
06:15 06:45 07:16 07:46
Code:
List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replaceAll(",", " ");
String after2 = after.replaceAll(" ", " ");
String after3 = after2.replaceAll("[", "");
String after4 = after3.replaceAll("]", "");
replaceAll replaces all occurrences that match a given regular expression. Since you just want to match a simple string, you should use replace instead:
List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replace(",", " ");
String after2 = after.replace(" ", " ");
String after3 = after2.replace("[", "");
String after4 = after3.replace("]", "");
To answer the main question, if you use replaceAll, make sure your 1st argument is a valid regular expression. For your example, you can actually reduce it to 2 calls to replaceAll, as 2 of the substitutions are identical.
List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replaceAll("[, ]", " ");
String after2 = after.replaceAll("\\[|\\]", "");
But, it looks like you're just trying to concatenate all the elements of a String list together. It's much more efficient to construct this string directly, by iterating your list and using StringBuilder:
StringBuilder builder = new StringBuilder();
for (String timeEntry: entry.getValue()) {
builder.append(timeEntry);
}
String after = builder.toString();

adding missing double quotes in file

I have a file which contains double quotes only to String types but i need to add missing double quotes to other fields and write into a file using java.
for example
123 ,6 ,"abc#yahoo.com"
"
should be converted to
"123 ","6 ","abc#yahoo.com" "
without trimming any value just adding the missing text qualifier around the fields. I have tried by splitting based on delimiter and then wrapping around quotes but it did not work.
please share if you have solved any issue like this.
You need to use string.replaceAll method.
string.replaceAll("(^|,)(?!\")([^,]+)", "$1\"$2\"");
DEMO
There's a solution without such a complicated regular expressions: you have to split your input by , and wrap the resulting Strings:
String[] splitted = input.split(",");
for (int i = 0; i < splitted.size(); ++i) {
if (splitted[i].charAt(0) != '"') {
splitted[i] = "\"" + splitted[i] + "\"";
}
}
String output = String.join(",", Arrays.asList(splitted)); // or any other joining technic, this is from Java 8
You can easily do it by using split() method from String class and just add quote when you need it.
Basically, I would try something like this:
public static void main (String... args) {
String st = "123 ,6 ,\"abc#yahoo.com";
String[] results = st.split(",");
String result = "";
for (String s : results) {
if (!s.startsWith("\""))
s = "\"" + s + "\"";
if (!s.endsWith("\""))
s+="\"";
s+=",";
result += s;
}
System.out.println(st);
System.out.println("-------------");
System.out.println(result);
}
This keep spaces and add some missing quotes.
I tried and the below is working...
public static void test()
{
String str = "123 ,6 ,\"abc#yahoo.com \"";
String result = "",temp="";
StringTokenizer token = new StringTokenizer(str,",");
while(token.hasMoreTokens())
{
temp = token.nextToken();
if(!temp.startsWith("\""))
result += "\""+temp+"\"";
else
result += temp;
}
System.out.println(result);
}
Please check...
Try using a simple foreach and if loop to check if the value has double quotes then add quotes to the values.
for(Object obj:YourContainer){
if(!value.contains("\"")){
String s = "\"" + value + "\"";
}
}
If you are getting fields like ""Test"" with double double quotes, try using the replace function.
String s;
for(Object obj:YourContainer){
if(!value.contains("\"")){
s = "\"" + value + "\"";
}
s = s.replace("\"\"","\"");
}

Check a particular string and delete part of string in android

I have a string format stored in shared preference. I would like to check if a particular word exists. If yes, then delete those few words which start from x and ends at y.
Something like this: For example:
String items = "Veggies=Beans-Carrot-Potato-Onions--DailyUse=Milk-Yogurt-Soap--Fruits=Apple-Banana-Grapes-Pears";
I would like to check if the above string items has "DailyUse=" if so delete all the words that are after "DailyUse=" until "--". So that my string looks like:
String Newitems = "Veggies=Beans-Carrot-Potato-Onions--Fruits=Apple-Banana-Grapes-Pears";
Is this possible? If so, how do I go about doing this?
Thanks!
Try this.
public static void main(String[] args) {
String items = "Veggies=Beans-Carrot-Potato-Onions--DailyUse=Milk-Yogurt-Soap--Fruits=Apple-Banana-Grapes-Pears";
String[] newItems = items.split("--");
System.out.println(newItems[0] + "--"+ newItems[2]);
}
I tried to put the DailyUse element in first, second and third position and this code seems to work. I think it can be improved, but here's an idea.
String items = "DailyUse=Milk-Yogurt-Soap--Veggies=Beans-Carrot-Potato-Onions--Fruits=Apple-Banana-Grapes-Pears";
String result = "";
if (items.contains("--DailyUse=")){ // not in first position
String[] a = items.split("--DailyUse=");
result = a[0];
if (a[1].contains("--")){ // Daily use is not the last element
String[] b = a[1].split("--");
result = result + "--" + b[1] ;
}
}
else if (items.contains("DailyUse=")){ // first position
String[] b = items.split("--");
result = items.replace(b[0]+"--", ""); // Delete the dailyuse part
}
Using regex
String [] tests = {
"DailyUse=Milk-Yogurt-Soap--Veggies=Beans-Carrot-Potato-Onions--DailyUse=Milk-Yogurt-Soap--Fruits=Apple-Banana-Grapes-Pears--DailyUse=Milk-Yogurt-Soap"
,"DailyUse=Milk-Yogurt-Soap"
,"DailyUse=Milk-Yogurt-Soap--DailyUse=Milk-Yogurt-Soap"
};
String key = "DailyUse";
for (String test : tests) {
String newItems = test;
// Replace only one at beginning
String regexp = "(^" + key + "=.+?(--|$))";
while(newItems.matches(regexp)) {
newItems = newItems.replaceAll(regexp, "");
}
// Regex to replace all other
regexp = "(--" + key + "=.+?)(--|$)";
newItems = newItems.replaceAll(regexp,"$2");
System.out.println("Before " + test);
System.out.println("After " + newItems);
}
UPDATE based on comments

Regex to match "path/*.extension"

I am trying to find a regular expression that would match the following format:
path/*.file_extension
For example:
temp/*.jpg
usr/*.pdf
var/lib/myLib.so
tmp/
Using the regex, I want to store the matching parts into a String array, such as:
String[] tokens;
// regex magic here
String path = tokens[0];
String filename = tokens[1];
String extension = tokens[2];
In case of the last case tmp/, that contains no filename and extension, then token[1] and token[2] would be null.
In case of the:
usr/*.pdf
then the token[1] would contain only the string "*".
Thank you very much for your help.
If you can use Java7 then you can use named groups like this
String data = "temp/*.jpg, usr/*.pdf, var/lib/*.so, tmp/*, usr/*, usr/*.*";
Pattern p = Pattern
.compile("(?<path>(\\w+/)+)((?<name>\\w+|[*]))?([.](?<extension>\\w+|[*]))?");
Matcher m = p.matcher(data);
while (m.find()) {
System.out.println("data=" + m.group());
System.out.println("path=" + m.group("path"));
System.out.println("name=" + m.group("name"));
System.out.println("extension=" + m.group("extension"));
System.out.println("------------");
}
This code should wotk:
String line = "var/lib/myLib.so";
Pattern p = Pattern.compile("(.+?(?=/[^/]*$))/([^.]+)\\.(.+)$");
Matcher m = p.matcher(line);
List<String> tokens = new ArrayList<String>();
if (m.find()) {
for (int i=1; i <= m.groupCount(); i++) {
tokens.add(m.group(i));
}
}
System.out.println("Tokens => " + tokens);
OUTPUT:
Tokens => [var/lib, myLib, so]
I'm assuming you're using Java. This should work:
Pattern.compile("path/(.*?)(?:\\.(file_extension))?");
Why use a regular expression?
I personally find lastIndexOf more readable.
String path;
String filename;
#Nullable String extension;
// Look for the last slash
int lastSlash = fullPath.lastIndexOf('/');
// Look for the last dot after the last slash
int lastDot = fullPath.lastIndexOf('.', lastSlash + 1);
if (lastDot < 0) {
filename = fullPath.substring(lastSlash + 1);
// If there is no dot, then there is no extension which
// is distinct from the empty extension in "foo/bar."
extension = null;
} else {
filename = fullPath.substring(lastSlash + 1, lastDot);
extension = fullPath.substring(lastDot + 1);
}
On a different approach, a simple usage of 'substring()/lastIndexOf()' methods should serve the purpose:
String filePath = "var/lib/myLib.so";
String fileName = filePath.substring(filePath.lastIndexOf('/')+1);
String path = filePath.substring(0, filePath.lastIndexOf('/'));
String fileName = fileName.substring(0, fileName.lastIndexOf('.'));
String extension = fileName.substring(fileName.lastIndexOf('.')+1);
Please Note: You need to handle the alternate scenarios e.g. file path without extension.

Categories

Resources