adding missing double quotes in file - java

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("\"\"","\"");
}

Related

Multiple string replacements without affecting substituted text in subsequent iterations

I've posted about letters earlier, but this is an another topic, I have a json response that contain 2 objects, from and to , from is what to change, and to is what it will be changed to .
My code is :
// for example, the EnteredText is "ab b test a b" .
EnteredString = EnteredText.getText().toString();
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
String Original = jo_inside.getString("from");
String To = jo_inside.getString("to");
if(isMethodConvertingIn){
EnteredString = EnteredString.replace(" ","_");
EnteredString = EnteredString.replace(Original,To + " ");
} else {
EnteredString = EnteredString.replace("_"," ");
EnteredString = EnteredString.replace(To + " ", Original);
}
}
LoadingProgress.setVisibility(View.GONE);
SetResultText(EnteredString);
ShowResultCardView();
For example, the json response is :
{
"Response":[
{"from":"a","to":"bhduh"},{"from":"b","to":"eieja"},{"from":"tes","to":"neesj"}
]
}
String.replace() method won't work here, because first it will replace a to bhduh, then b to eieja, BUT here's the problem, it will convert b in bhduh to eieja, which i don't want to.
I want to perfectly convert the letters and "words" in the String according the Json, but that what i'm failing at .
New Code :
if(m_jArry.length() > 0){
HashMap<String, String> m_li;
EnteredString = EnteredText.getText().toString();
Log.i("TestAf_","Before Converting: " + EnteredString);
HashMap<String,String> replacements = new HashMap<String,String>();
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
String Original = jo_inside.getString("from");
String To = jo_inside.getString("to");
if(isMethodConvertingIn){
//EnteredString = EnteredString.replace(" ","_");
replacements.put(Original,To);
Log.i("TestAf_","From: " + Original + " - To: " + To + " - Loop: " + i);
//EnteredString = EnteredString.replace(" ","_");
//EnteredString = EnteredString.replace(Original,To + " ");
} else {
EnteredString = EnteredString.replace("_"," ");
EnteredString = EnteredString.replace("'" + To + "'", Original);
}
}
Log.i("TestAf_","After Converting: " + replaceTokens(EnteredString,replacements));
// Replace Logic Here
// When Finish, Do :
LoadingProgress.setVisibility(View.GONE);
SetResultText(replaceTokens(EnteredString,replacements));
ShowResultCardView();
Output :
10-10 19:51:19.757 12113-12113/? I/TestAf_: Before Converting: ab a ba
10-10 19:51:19.757 12113-12113/? I/TestAf_: From: a - To: bhduh - Loop: 0
10-10 19:51:19.757 12113-12113/? I/TestAf_: From: b - To: eieja - Loop: 1
10-10 19:51:19.757 12113-12113/? I/TestAf_: From: o - To: neesj - Loop: 2
10-10 19:51:19.758 12113-12113/? I/TestAf_: After Converting: ab a ba
You question would be clearer if you gave the expected output for the function.
Assuming it is: ab b test a b >>>> bhduheieja eieja neesjt bhduh eieja
then see the following, the key point in the Javadoc being "This will not repeat"
http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringUtils.html#replaceEach(java.lang.String,%20java.lang.String[],%20java.lang.String[])
Replaces all occurrences of Strings within another String.
A null reference passed to this method is a no-op, or if any "search
string" or "string to replace" is null, that replace will be ignored.
This will not repeat. For repeating replaces, call the overloaded
method.
Example 1
import org.apache.commons.lang3.StringUtils;
public class StringReplacer {
public static void main(String[] args) {
String input = "ab b test a b";
String output = StringUtils.replaceEach(input, new String[] { "a", "b", "tes" },
new String[] { "bhduh", "eieja", "neesj" });
System.out.println(input + " >>>> " + output);
}
}
Example 2
import org.apache.commons.lang3.StringUtils;
public class StringReplacer {
public static void main(String[] args) {
String input = "this is a test string with foo";
String output = StringUtils.replaceEach(input, new String[] { "a", "foo" },
new String[] { "foo", "bar"});
System.out.println(input + " >>>> " + output);
}
}
Try following:
Solution 1:
Traverse the String characters one by one and move the new String to a new StringBuffer or StringBuilder, then call toString() to get the result. This will need you to implement string matching algorithm.
Solution 2 (Using Regex):
For this, you must know the domain of your string. For example, it is [a-zA-Z] then other arbitrary characters (not part of domain) can be used for intermediate step. First replace the actual characters with arbitrary one then arbitrary ones with the target. In example below, [!##] are the arbitrary characters. These can be any random \uxxxx value as well.
String input = "a-b-c";
String output = input.replaceAll("[a]", "!").replaceAll("[b]", "#").replaceAll("[c]", "#");
output = output.replaceAll("[!]", "bcd").replaceAll("[#]", "cde").replaceAll("[#]", "def");
System.out.println("input: " + input);
System.out.println("Expected: bcd-cde-def");
System.out.println("Actual: " + output);
Your issue is quite common. To sum things up :
String test = "this is a test string with foo";
System.out.println(test.replace("a", "foo").replace("foo", "bar"));
Gives : this is bar test string with bar
Expected by you : this is foo test string with bar
You can use StrSubstitutor from Apache Commons Lang
But first you will have to inject placeholders in your string :
String test = "this is a test string with foo";
Map<String, String> valuesMap = new HashMap<>();
valuesMap.put("a", "foo");
valuesMap.put("foo", "bar");
String testWithPlaceholder = test;
// Preparing the placeholders
for (String value : valuesMap.keySet())
{
testWithPlaceholder = testWithPlaceholder.replace(value, "${"+value+"}");
}
And then, use StrSubstitutor
System.out.println(StrSubstitutor.replace(testWithPlaceholder, valuesMap));
It gives : this is foo test string with bar
Here is an method which is strictly just Java. I tried not to use any Java 8 methods here.
public static String translate(final String str, List<String> from, List<String> to, int index) {
StringBuilder components = new StringBuilder();
String token, replace;
int p;
if (index < from.size()) {
token = from.get(index);
replace = to.get(index);
p = 0;
for (int i = str.indexOf(token, p); i != -1; i = str.indexOf(token, p)) {
if (i != p) {
components.append(translate(str.substring(p, i), from, to, index + 1));
}
components.append(replace);
p = i + token.length();
}
return components.append(translate(str.substring(p), from, to, index + 1)).toString();
}
return str;
}
public static String translate(final String str, List<String> from, List<String> to) {
if (null == str) {
return null;
}
return translate(str, from, to, 0);
}
Sample test program
public static void main(String []args) {
String EnteredString = "aa hjkyu batesh a";
List<String> from = new ArrayList<>(Arrays.asList("a", "b", "tes"));
List<String> to = new ArrayList<>(Arrays.asList("bhduh", "eieja", "neesj"));
System.out.println(translate(EnteredString, from, to));
}
Output:
bhduhbhduh hjkyu eiejabhduhneesjh bhduh
Explaination
The algorithm is recursive, and it simply does the following
If a pattern found in the string matches a pattern in the from list
if there is any string before that pattern, apply the algorithm to that string
replace the found pattern with the corresponding pattern in the to list
append the replacement to the new string
discard the pattern in the from list and repeat the algorithm for the rest of the string
Otherwise append the rest of the string to the new string
You could use split like:
String[] pieces = jsonResponse.split("},{");
then you just parse the from and to in each piece and apply them with replace() then put the string back together again. (and please get your capitalization of your variables/methods right - makes it very hard to read the way you have it)
Apache Commons StringUtils::replaceEach does this.
String[] froms = new String[] {"a", "b"};
String[] tos = new String[] {"b","c"};
String result = StringUtils.replaceEach("ab", froms, tos);
// result is "bc"
Why not keep it very simple (if the JSON is always in same format, EG: from the same system). Instead of replacing from with to, replace the entire markup:
replace "from":"*from*" with "from":"*to*"
Why not just change the actual "to" and "from" labels? That way, you don't run into a situation where "bhudh" becomes "eieja". Just do a string replace on "from" and "to".

"missing ) after argument list" [duplicate]

I want to initialize a String in Java, but that string needs to include quotes; for example: "ROM". I tried doing:
String value = " "ROM" ";
but that doesn't work. How can I include "s within a string?
In Java, you can escape quotes with \:
String value = " \"ROM\" ";
In reference to your comment after Ian Henry's answer, I'm not quite 100% sure I understand what you are asking.
If it is about getting double quote marks added into a string, you can concatenate the double quotes into your string, for example:
String theFirst = "Java Programming";
String ROM = "\"" + theFirst + "\"";
Or, if you want to do it with one String variable, it would be:
String ROM = "Java Programming";
ROM = "\"" + ROM + "\"";
Of course, this actually replaces the original ROM, since Java Strings are immutable.
If you are wanting to do something like turn the variable name into a String, you can't do that in Java, AFAIK.
Not sure what language you're using (you didn't specify), but you should be able to "escape" the quotation mark character with a backslash: "\"ROM\""
\ = \\
" = \"
new line = \r\n OR \n\r OR \n (depends on OS) bun usualy \n enough.
taabulator = \t
Just escape the quotes:
String value = "\"ROM\"";
In Java, you can use char value with ":
char quotes ='"';
String strVar=quotes+"ROM"+quotes;
Here is full java example:-
public class QuoteInJava {
public static void main (String args[])
{
System.out.println ("If you need to 'quote' in Java");
System.out.println ("you can use single \' or double \" quote");
}
}
Here is Out PUT:-
If you need to 'quote' in Java
you can use single ' or double " quote
Look into this one ... call from anywhere you want.
public String setdoubleQuote(String myText) {
String quoteText = "";
if (!myText.isEmpty()) {
quoteText = "\"" + myText + "\"";
}
return quoteText;
}
apply double quotes to non empty dynamic string. Hope this is helpful.
This tiny java method will help you produce standard CSV text of a specific column.
public static String getStandardizedCsv(String columnText){
//contains line feed ?
boolean containsLineFeed = false;
if(columnText.contains("\n")){
containsLineFeed = true;
}
boolean containsCommas = false;
if(columnText.contains(",")){
containsCommas = true;
}
boolean containsDoubleQuotes = false;
if(columnText.contains("\"")){
containsDoubleQuotes = true;
}
columnText.replaceAll("\"", "\"\"");
if(containsLineFeed || containsCommas || containsDoubleQuotes){
columnText = "\"" + columnText + "\"";
}
return columnText;
}
suppose ROM is string variable which equals "strval"
you can simply do
String value= " \" "+ROM+" \" ";
it will be stored as
value= " "strval" ";

How to detect the letters in a String and switch them?

How to detect the letters in a String and switch them?
I thought about something like this...but is this possible?
//For example:
String main = hello/bye;
if(main.contains("/")){
//Then switch the letters before "/" with the letters after "/"
}else{
//nothing
}
Well, if you are interested in a cheeky regex :P
public static void main(String[] args) {
String s = "hello/bye";
//if(s.contains("/")){ No need to check this
System.out.println(s.replaceAll("(.*?)/(.*)", "$2/$1")); // () is a capturing group. it captures everything inside the braces. $1 and $2 are the captured values. You capture values and then swap them. :P
//}
}
O/P :
bye/hello --> This is what you want right?
Use String.substring:
main = main.substring(main.indexOf("/") + 1)
+ "/"
+ main.substring(0, main.indexOf("/")) ;
You can use String.split e.g.
String main = "hello/bye";
String[] splitUp = main.split("/"); // Now you have two strings in the array.
String newString = splitUp[1] + "/" + splitUp[0];
Of course you have to also implement some error handling when there is no slash etc..
you can use string.split(separator,limit)
limit : Optional. An integer that specifies the number of splits, items after the split limit will not be included in the array
String main ="hello/bye";
if(main.contains("/")){
//Then switch the letters before "/" with the letters after "/"
String[] parts = main.split("/",1);
main = parts[1] +"/" + parts[0] ; //main become 'bye/hello'
}else{
//nothing
}
Also you can use StringTokenizer to split the string.
String main = "hello/bye";
StringTokenizer st = new StringTokenizer(main,"\");
String part1 = st.nextToken();
String part2 = st.nextToken();
String newMain = part2 + "\" + part1;

Replacing last character in a String with 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("," , " ");

how to process string in java

I want to make strings like "a b c" to "prefix_a prefix_b prefix_c"
how to do that in java?
You can use the String method: replaceAll(String regex,String replacement)
String s = "a xyz c";
s = s.replaceAll("(\\w+)", "prefix_$1");
System.out.println(s);
You may need to tweek the regexp to meet your exact requirements.
Assuming a split character of a space (" "), the String can be split using the split method, then each new String can have the prefix_ appended, then concatenated back to a String:
String[] tokens = "a b c".split(" ");
String result = "";
for (String token : tokens) {
result += ("prefix_" + token + " ");
}
System.out.println(result);
Output:
prefix_a prefix_b prefix_c
Using a StringBuilder would improve performance if necessary:
String[] tokens = "a b c".split(" ");
StringBuilder result = new StringBuilder();
for (String token : tokens) {
result.append("prefix_");
result.append(token);
result.append(" ");
}
result.deleteCharAt(result.length() - 1);
System.out.println(result.toString());
The only catch with the first sample is that there will be an extraneous space at the end of the last token.
hope I'm not mis-reading the question. Are you just looking for straight up concatenation?
String someString = "a";
String yourPrefix = "prefix_"; // or whatever
String result = yourPrefix + someString;
System.out.println(result);
would show you
prefix_a
You can use StringTokenizer to enumerate over your string, with a "space" delimiter, and in your loop you can add your prefix onto the current element in your enumeration. Bottom line: See StringTokenizer in the javadocs.
You could also do it with regex and a word boundary ("\b"), but this seems brittle.
Another possibility is using String.split to convert your string into an array of strings, and then loop over your array of "a", "b", and "c" and prefix your array elements with the prefix of your choice.
You can split a string using regular expressions and put it back together with a loop over the resulting array:
public class Test {
public static void main (String args[]) {
String s = "a b c";
String[] s2 = s.split("\\s+");
String s3 = "";
if (s2.length > 0)
s3 = "pattern_" + s2[0];
for (int i = 1; i < s2.length; i++) {
s3 = s3 + " pattern_" + s2[i];
}
System.out.println (s3);
}
}
This is C# but should easily translate to Java (but it's not a very smart solution).
String input = "a b c";
String output (" " + input).Replace(" ", "prefix_")
UPDATE
The first solution has no spaces in the output. This solution requires a place holder symbol (#) not occuring in the input.
String output = ("#" + input.Replace(" ", " #")).Replace("#", "prefix_");
It's probably more efficient to use a StringBuilder.
String input = "a b c";
String[] items = input.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
StringBuilder sb = new StringBuilder();
foreach (String item in items)
{
sb.Append("prefix_");
sb.Append(item);
sb.Append(" ");
}
sb.Length--;
String output = sb.ToString();

Categories

Resources