How to replace spaces in Java in a efficient and better way - java

I referred to this link
http://www.crazyforcode.com/replace-spaces-string-%20/
and couldn't find any similar implementation for Java in Stackoverflow
I have implemented a similar logic to replace spaces to %20 using the below code.
String sen="I need to replace all the spaces to %20";
String[] arr = sen.split(" ");
StringBuffer buff = new StringBuffer();
for (String str : arr) {
buff.append(str);
buff.append("%20");
}
But there are many issues with the logic, like it adds %20 to the last of every sentence. Is there any efficient way of doing this ??

The best and the most efficient way of doing this is to use a inbuilt library to implement this for you. You can use
java.net.URLEncoder
and you can find the API here http://docs.oracle.com/javase/8/docs/api/java/net/URLEncoder.html#encode-java.lang.String-java.lang.String- or here https://docs.oracle.com/javase/7/docs/api/java/net/URLEncoder.html

if you don't want to use predefined methods, do the following:
String str = "t e s t";
str = str.replace(" ", "%20");
System.out.println(str);
This will print out "t%20e%20s%20t".

You can try to substring the output of the StringBuffer.
String sen = "I need to replace all the spaces to %20";
String[] arr = sen.split(" ");
StringBuffer buffer = new StringBuffer();
for (String str : arr) {
buffer.append(str);
buffer.append("%20");
}
String bufferString = buffer.toString();
String stringWithoutSpaces = bufferString.substring(0, bufferString.length() - 3);
but another more simple solution would be:
sen = sen.trim().replaceAll(" ", "%20");

Don't know Java, but if its like c++ a bit, use the fastest method.
It might be old fashioned, but still the fastest.
pseudocode
buff = "";
if ( arr.size() > 0 ) {
buff = arr[0];
for (int i=1; i<arr.size(); i++)
buff.append("%20" + arr[i] );
}

Related

Get values till until a character(include the checking character) using stringbuilder

How to check if a begining of line is "A" followed with anything is Ablahblablah
StringBuilder sb = new StringBuilder();
String[] lines1 = sb.toString().split("\\n");
for(String getVal: lines1){
while(getVal.contains("^A\\w*")){
temp.append(getVal);//If found store all the former values and line including A + 2 characters in a temp buffer
}
}
System.out.println("temp = " + temp.toString());
output
temp =
Temp returns empty.
Am I doing anything wrong.
UPDATE
used : if(getVal.startsWith("6000")){
I am getting the desired output.
Any issues in this logic.
how to delete the temp from existing sb?
You need to use matches() method, not contains().
Why not just do
if (getVal.startWith("A")) {
...
like this:
StringBuilder sb = new StringBuilder();
.
.
.
String[] lines1 = sb.toString().split("\\n");
for(String getVal: lines1){
while(getVal.matches("A\\w*")){
temp.append(getVal);//If found store all the former values and line including A + 2 characters in a temp buffer
}
}
System.out.println("temp = " + temp.toString());
Thanks every one
I found the answer
String[] lines1 = sb.toString().split("\\n");
StringBuilder temp = new StringBuilder();
for(String getVal: lines1){
if(getVal.startsWith("6000")){
temp.append(getVal);
break;
}
else{
temp.append(getVal);
}
temp.append("\n");
}
Its because of scope of temp.have you declared variable temp outside of loop?

Problems reading text file data in Java

I have this code:
BufferedReader br =new BufferedReader(new FileReader("userdetails.txt"));
String str;
ArrayList<String> stringList = new ArrayList<String>();
while ((str=br.readLine())!=null){
String datavalue [] = str.split(",");
String category = datavalue[0];
String value = datavalue[1];
stringList.add(category);
stringList.add(value);
}
br.close();
it works when the variables category and value do not have a comma(,),however the values in the variable value does contain commas.Is there a way that I can split the index of the without using comma?
The solution is given bellow:
BufferedReader br =new BufferedReader(new FileReader("userdetails.txt"));
String str;
ArrayList<String> stringList = new ArrayList<String>();
while ((str=br.readLine())!=null){
int firstIndexOfComma = str.indexOf(',');
String category = str.substring(0, firstIndexOfComma);
String value = str.substring(firstIndexOfComma + 1);
stringList.add(category);
stringList.add(value);
System.out.println(category+" "+value);
}
br.close();
When data has ',' it is generally called CSV file. OpenCSV is fairly used library to handle it. The format looks simple, but it has it quirks. See wikipedia for some details
If I understood you correctly:
String str = "category,vvvv,vvv";
int i = str.indexOf(',');
String category = str.substring(0, i);
String value = str.substring(i + 1);
split() uses regex.
if the reader code works perfectly, do
str.split("\\,");
Not 100% sure, but couldnt you just do
String datavalue [] = str.split("--");
or something?
sample file:
x,y,z--123--Hello World
output:
"x,y,z",
"123",
"Hello World"

Efficiently parsing and writing to a file in Java

I have a file that has no new line characters. I want a new line character every 160 characters.
To do this, I read the file, and then do:
String newLine = "";
int lineSize = 160;
char[] line = new char[lineSize];
while (rEntrada.read(line) > 0) {
newLine = new String(line);
String parsedLine = parseLine(newLine, date);
fw.write(parsedLine);
}
where parseLine takes care of some extra parsing of the line. My main question is if doing a "new String" inside a while loop is inefficient or not recommended or if you guys see anything that could be done better in this code. I'm really trying to get better at coding!
Thanks!
Try this.
First read the single line.
FileReader r = new FileReader(new File("<file-name>"));
// A buffered reader is fast
BufferedReader = reader = new BufferedReader(r);
String line = reader.readLine();
// Also use try-catch blocks!
Now iterate over the string and insert a \n at every 160th position.
StringBuilder sb = new StringBuilder();
int counter = 0;
for (int i=0; i<line.length(); i++){
sb.append(line.charAt(i));
counter++;
if (counter==160){
sb.append("\n");
counter = 0;
}
}
line = sb.toString();
Now you could write this line to the file.
It looks good to me, the only inefficiency I can see is if parseLine could be written better, possibly being passed line instead of newLine. It depends on what parseLine actually does.
Take a look at StringBuffer and see if it isn't usable in this case.
StringBuffer API Documentation
StringBuilder may also be of interest if you're not multi-threaded.

Split text file into Strings on empty line

I want to read a local txt file and read the text in this file. After that i want to split this whole text into Strings like in the example below .
Example :
Lets say file contains-
abcdef
ghijkl
aededd
ededed
ededfe
efefeef
efefeff
......
......
I want to split this text in to Strings
s1 = abcdef+"\n"+ghijkl;
s2 = aededd+"\n"+ededed;
s3 = ededfe+"\n"+efefeef+"\n"+efefeff;
........................
I mean I want to split text on empty line.
I do know how to read a file. I want help in splitting the text in to strings
you can split a string to an array by
String.split();
if you want it by new lines it will be
String.split("\\n\\n");
UPDATE*
If I understand what you are saying then john.
then your code will essentially be
BufferedReader in
= new BufferedReader(new FileReader("foo.txt"));
List<String> allStrings = new ArrayList<String>();
String str ="";
while(true)
{
String tmp = in.readLine();
if(tmp.isEmpty())
{
if(!str.isEmpty())
{
allStrings.add(str);
}
str= "";
}
else if(tmp==null)
{
break;
}
else
{
if(str.isEmpty())
{
str = tmp;
}
else
{
str += "\\n" + tmp;
}
}
}
Might be what you are trying to parse.
Where allStrings is a list of all of your strings.
The below code would work even if there are more than 2 empty lines between useful data.
import java.util.regex.*;
// read your file and store it in a string named str_file_data
Pattern p = Pattern.compile("\\n[\\n]+"); /*if your text file has \r\n as the newline character then use Pattern p = Pattern.compile("\\r\\n[\\r\\n]+");*/
String[] result = p.split(str_file_data);
(I did not test the code so there could be typos.)
I would suggest more general regexp:
text.split("(?m)^\\s*$");
In this case it would work correctly on any end-of-line convention, and also would treat the same empty and blank-space-only lines.
It may depend on how the file is encoded, so I would likely do the following:
String.split("(\\n\\r|\\n|\\r){2}");
Some text files encode newlines as "\n\r" while others may be simply "\n". Two new lines in a row means you have an empty line.
Godwin was on the right track, but I think we can make this work a bit better. Using the '[ ]' in regx is an or, so in his example if you had a \r\n that would just be a new line not an empty line. The regular expression would split it on both the \r and the \n, and I believe in the example we were looking for an empty line which would require a either a \n\r\n\r, a \r\n\r\n, a \n\r\r\n, a \r\n\n\r, or a \n\n or a \r\r
So first we want to look for either \n\r or \r\n twice, with any combination of the two being possible.
String.split(((\\n\\r)|(\\r\\n)){2}));
next we need to look for \r without a \n after it
String.split(\\r{2});
lastly, lets do the same for \n
String.split(\\n{2});
And all together that should be
String.split("((\\n\\r)|(\\r\\n)){2}|(\\r){2}|(\\n){2}");
Note, this works only on the very specific example of using new lines and character returns. I in ruby you can do the following which would encompass more cases. I don't know if there is an equivalent in Java.
.match($^$)
#Kevin code works fine and as he mentioned that the code was not tested, here are the 3 changes required:
1.The if check for (tmp==null) should come first, otherwise there will be a null pointer exception.
2.This code leaves out the last set of lines being added to the ArrayList. To make sure the last one gets added, we have to include this code after the while loop: if(!str.isEmpty()) { allStrings.add(str); }
3.The line str += "\n" + tmp; should be changed to use \n instead if \\n. Please see the end of this thread, I have added the entire code so that it can help
BufferedReader in
= new BufferedReader(new FileReader("foo.txt"));
List<String> allStrings = new ArrayList<String>();
String str ="";
List<String> allStrings = new ArrayList<String>();
String str ="";
while(true)
{
String tmp = in.readLine();
if(tmp==null)
{
break;
}else if(tmp.isEmpty())
{
if(!str.isEmpty())
{
allStrings.add(str);
}
str= "";
}else
{
if(str.isEmpty())
{
str = tmp;
}
else
{
str += "\n" + tmp;
}
}
}
if(!str.isEmpty())
{
allStrings.add(str);
}

Cannot start new line with "\n"?

I am working on a project and there is a small part of it really confusing me.
Say I have a String array :
String[]text = {"string","array"};
for example.
And I want to make it to a single String with a new line "\n" between every single word.
So here is my code
public String setText(String [] text) throws UnsupportedEncodingException{
StringBuffer result = new StringBuffer();
String newline = System.getProperty("line.separator");
if (text.length > 0) {
result.append(text[0]);
for (int i=1; i<text.length; i++) {
result.append(newline);
result.append(text[i]);
}
}
return result.toString();
}
My code doesnt work. The return value is a single string but when I use it, it is still in one line.
Anyone can help me with this?
Thank you
Allan
Did you see what System.getProperty("line.separator"); returns?
In different OS it will be different symbols \n - Linux and \r\n in Windows
Try to use
System.getProperty("line.separator", "\r\n"); or System.getProperty("line.separator", "\n");
Depends on how you use the result. Have you tried writing it to System.out / a file or anything similar?
I would recommend using Joiner from Google's Guava library.
Joiner.on(System.getProperty("line.separator")).join(text)

Categories

Resources