Removed comma from last while working with StringBuilder - java

I've the following Java program and I don't want "," to be assign after my last element, what to do ?
String range = "400-450";
Integer startRange = null;
Integer endRange = null;
StringTokenizer st = new StringTokenizer(range,"-");
while(st.hasMoreTokens()) {
startRange = Integer.parseInt(st.nextToken());
endRange= Integer.parseInt(st.nextToken());
}
StringBuilder sb = new StringBuilder();
for (int i = startRange; i <= endRange; i++) {
sb.append(i).append(",");
}
System.out.println(sb);
The output should be
400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450 --> without comma at last

For Java 8 you could switch to new class StringJoiner which has beed added for exactly that purpose:
StringJoiner sb = new StringJoiner(",");
for (int i = startRange; i <= endRange; i++) {
sb.add(String.valueOf(i));
}
System.out.println(sb.toString());
Doing it manually, I'd suggest adding the comma before the item and then use substring(1):
for (int i = startRange; i <= endRange; i++) {
sb.append(",").append(i);
}
//Check for empty before!
System.out.println(sb.substring(1));

As #Jan says, use StringJoiner if you have Java8. Otherwise you could add a separator before the new entry and treat the first item differently by initialising the separator to blank.
String separator = "";
for (int i = startRange; i <= endRange; i++) {
sb.append(separator).append(i);
separator = ",";
}
This is the Java8 version
StringJoiner sb = new StringJoiner(",");
for (int i = startRange; i <= endRange; i++) {
sb.add(String.valueOf(i));
}

Just simple as
for (int i = startRange; i <= endRange; i++) {
sb.append(i);
if(i != endRange)
sb.append(",");
}

Use Joiner (guava) for Java < 8.
List<Integer> numbers = Lists.newArrayList(1, 3, 4, 5, 23);
System.out.println(Joiner.on(",").join(numbers));
And the output is:
1,3,4,5,23

Just let the last loop appending the commas stop before the last element is reached:
String range = "400-450";
Integer startRange = null;
Integer endRange = null;
StringTokenizer st = new StringTokenizer(range,"-");
while(st.hasMoreTokens()) {
startRange = Integer.parseInt(st.nextToken());
endRange= Integer.parseInt(st.nextToken());
}
StringBuilder sb = new StringBuilder();
// here, the "<=" was changed to "<"
for (int i = startRange; i < endRange; i++) {
sb.append(i).append(",");
}
// append last element
sb.append(endrange)
System.out.println(sb);

You are appending "," after each i
try to append "," only if you didn't reach the endRange
do:
for (int i = startRange; i <= endRange; i++) {
sb.append(i)
if (i != endRange)
sb.append(",");
}
this way "," will not be added to sb after last number.

Related

How do I find the longest words in a string?

I want to find the longest words in a given String.
The following code checks for the longest word, but I want every other word with the same length as well.
try (BufferedReader fileInputReader = new BufferedReader(new FileReader(filePath))){
String line = fileInputReader.readLine();
line = line.replaceAll("[^äÄöÖüÜßa-zA-Z ]", "");
String[] sentence = line.split(" ");
String longestWord = "";
for (int i = 0; i < sentence.length; i++) {
if (sentence[i].length() > longestWord.length()) {
longestWord = sentence[i];
}
}
System.out.println(longestWord);
}
Then you have to use a collection of these longestWords, e.g.
ArrayList<String> longestWords = new ArrayList<String>();
int longestWordLength = 0;
for (int i = 0; i < sentence.length; i++) {
if (sentence[i].length() > longestWordLength) { // longer
longestWordLength = sentence[i].length();
longestWords.clear();
longestWords.add(sentence[i]);
}
else if (sentence[i].length() == longestWordLength) { // same length
longestWords.add(sentence[i]);
}
}
for (int i = 0; i < longestWords.size(); ++i)
System.out.println(longestWords.get(i));
try(BufferedReader fileInputReader = new BufferedReader(new FileReader(filePath))){
String line = fileInputReader.readLine();
line = line.replaceAll("[^äÄöÖüÜßa-zA-Z ]", "");
String[] sentence = line.split(" ");
ArrayList<String> longestWord = new ArrayList<>();
int maxLength = 1;
for(int i = 0; i < sentence.length; i++){
if(sentence[i].length() > maxLength){
longestword.clear();
longestWord.add(sentence[i]);
maxLength=sentece[i].length();
}
else if(sentence[i].length() == maxLength)
{
longestWord.add(sentence[i]);
}
}
System.out.println(longestWord);
}

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space while using util Packages

My problem statement:
There will be given set of words in a file (>5000 words). We need return a list of anagrams separated by comma(,) in each string(set of anagrams)
Eg: [alter,later, part,trap, elbow,below, listen,silent , tensil ]
Exception:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:3210)
at java.util.Arrays.copyOf(Arrays.java:3181)
at java.util.ArrayList.grow(ArrayList.java:265)
at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:239)
at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:231)
at java.util.ArrayList.add(ArrayList.java:462)
at FindAnagrams01.anagramsList(FindAnagrams01.java:25)
at FindAnagrams01.main(FindAnagrams01.java:7)
My code is :
public static List<String> anagramsList(String filePath) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String str = br.readLine();
List<List<String>> result = new ArrayList<List<String>>(10000);
HashMap<String, ArrayList<String>> map = new HashMap<String,ArrayList<String>>(10000);
while(str != null) {
char[] arr = new char[26];
for(int i = 0; i < str.length(); i++) {
arr[str.charAt(i) - 'a']++;
}
String ns = new String(arr);
if(map.containsKey(ns)){
map.get(ns).add(str);
} else {
ArrayList<String> al = new ArrayList<String>(10000);
al.add(str);
map.put(ns, al);
}
}
br.close();
result.addAll(map.values());
String res[] = new String[10000];
for(int i = 0; i < result.size(); i++) {
int isIntial = 0;
for(String j : result.get(i)) {
if ((result.get(i).size()) > 1) {
if (isIntial == 0) {
res[i] = j;
isIntial = 1;
}
else
res[i] += "," + j;
}
}
}
List<String> angrms = new ArrayList<String>(10000);
for (int i = 0; i < res.length; i++) {
if (res[i] != null)
angrms.add(res[i]);
}
return angrms;
}
The problem is that this is an infinite loop:
while(str != null) {
char[] arr = new char[26];
for(int i = 0; i < str.length(); i++) {
arr[str.charAt(i) - 'a']++;
}
String ns = new String(arr);
if(map.containsKey(ns)){
map.get(ns).add(str);
} else {
ArrayList<String> al = new ArrayList<String>(10000);
al.add(str);
map.put(ns, al);
}
}
because str is not altered within the loop body. As a result, you end up repeatedly adding strings to an array list until you eventually run out of memory.
There are other problems with your code ... but this explains your OOME.

Compare two strings and store the index in integer array

I have :
String1[] having Number,Quantity,Unit of Measure,Find Number parameters
String2[] having Action,Level,Number,Organization ID,Container,Revision,View,Quantity,Unit of Measure,Reference Designators,Trace Code,Find Number,Line Number,Component Reference,Quantity Option,Inclusion Option,Type
this parameters I have compare both the strings split them by commas using for loop. I want string1 found in string2 at which index. I want to store those index in one integer.
Please give any idea.
String[] col=col_name.split(",");
BufferedReader br = new BufferedReader(new FileReader("file.csv"));
String header = br.readLine();
if(header!=null)
{
String[] two = header.split(",");
System.out.println(header);
// String[] columns = header.split(",");
int[] indices = new int[20];
for (int i = 0; i < two.length; i++) {
for (int j = 0; j < col.length; j++) {
if(two[i].equals(col[j])){
System.out.println("("+i+","+j+")");
indices[i]=i;
}
}
Thanks in Advance
You can use the list.indexOf(Object o) method. Example:
String[] col=col_name.split(",");
BufferedReader br = new BufferedReader(new FileReader("file.csv"));
String header = br.readLine();
if(header!=null)
{
String[] two = header.split(",");
System.out.println(header);
int[] indices = new int[col.length];
for(int j = 0; j < col.length; j++){
indices[j]=Arrays.asList(two).indexOf(col[j]);
}
System.out.println(Arrays.toString(indices));
}

Reverse a string as per length of first word

I am new to Java Strings.
Actually I have the code to reverse words:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test2 {
public static void main(String[] args) throws IOException
{
System.out.println("enter a sentence");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String rev =br.readLine();
String [] bread = rev.split(" ");
for(int z =bread.length-1;z>=0;z--)
{
System.out.println(bread[z]);
}
}
}
For the above code I get:
Input :Bangalore is a city
Output: City is a Bangalore
But I want the output to be like below:
Input: Bangalore is a city
Output:cityaisba ng a lore
Another Example:
Input: Hello Iam New To Java.Java is object Oriented language.
Output: langu age Ori en tedo bjec ti sjava. javaToNe wIamolleH
Please help me out
Here is one way you could do it:
String rev = br.readLine();
String [] bread = rev.split(" ");
int revCounter = 0;
for(int z = bread.length - 1; z >= 0; z--)
{
String word = bread[z];
for(int i = 0; i < word.length(); i++)
{
// If char at current position in 'rev' was a space then
// just print space. Otherwise, print char from current word.
if(rev.charAt(revCounter) == ' ')
{
System.out.print(' ');
i--;
}
else
System.out.print(word.charAt(i));
revCounter++;
}
}
When I run your code I get following result:
city
a
is
Bangalore
So to have it in a single line, why don't you add a space and print a single line?
System.out.println("enter a sentence");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String rev = br.readLine();
String[] bread = rev.split(" ");
for (int z = bread.length - 1; z >= 0; z--) {
System.out.print(bread[z] + " ");
}
I didn't check the validity of your code like GHajba did. But if you want spaces to remain on specific places it might be an option to remove all spaces and put them back according to their index in the original String.
Remove all
newBread = newBread.replace(" ", "");
Put them back
StringBuilder str = new StringBuilder(newBread);
for (int index = oldBread.indexOf(" ") ;
index >= 0 ;
index = oldBread.indexOf(" ", index + 1))
{
str.insert(index, ' ');
}
newBread = str.toString();
I came up with this quick and there might be better ways to do this, maybe without StringBuilder, but this might help you until you find a better way.
Try with this (i've used a string as input):
String original = "Bangalore is a city";
System.out.println("Original : "+original);
StringBuilder inverted = new StringBuilder();
StringBuilder output = new StringBuilder();
String temp = "";
String[] split = original.split("\\s+");
for (int i = split.length - 1; i >= 0; i--) {
inverted.append(split[i]);
}
temp = inverted.toString();
for (String string : split) {
int currLenght = string.length();
String substring = temp.substring(0,currLenght);
temp = temp.replaceAll(substring, "");
output.append(substring).append(" ");
}
System.out.println("Converted : "+output.toString());
Append the reversed words without the spaces into a StringBuffer.
StringBuffer b = new StringBuffer();
for (int i = bread.length-1; i >= 0 ; i--) {
b.append(bread[i]);
}
Then insert the spaces of the original String into the StringBuffer.
int spaceIndex, prevIndex = 0;
while ((spaceIndex = rev.indexOf(" ", prevIndex + 1)) != -1) {
b.insert(spaceIndex, ' ');
prevIndex = spaceIndex;
}

convert List<String> to a static string if possible

I am trying to wrap my head around List<String> I have a dynamicly created array List<String> selected_tags That I would like to convert to break apart the elements and place a "%" inbetween each element so I can use the new string in a http call.
Creat my new List :
public List<String> selected_tags = new ArrayList<String>();
Fill my List string
for (int i = 0; i < tags.length; i++) {
if (selected[i] == true){
selected_tags.add(tags[i]);
}
}
I then need to use selected_tags in my url
HttpGet httpPost = new HttpGet("http://www.mywebsite.com/scripts/getData.php?tags="+ BROKEN DOWN LIST<STRING>);
I would like for it to look like
HttpGet httpPost = new HttpGet("http://www.mywebsite.com/scripts/getData.php?tags=tag1%tag2%tag3);
StringBuilder s = new StringBuilder();
boolean first = true;
for (String tag : selected_tags) {
if (!first)
s.append("%");
else
first = false;
s.append(tag);
}
String myUrlString = "tags=" + s.toString();
actually, you should have something like
StringBuilder sb = new StringBuilder();
if(selected_tags.size() > 0) {
sb.append(selected_tags.get(0);
for(int i = 1 ; i < selected_tags.size(); i++) {
sb.append("%");
sb.append(selected_tags.get(i));
}
}
return sb.toString();
StringBuilder result = new StringBuilder();
String prepend = "tags=";
for( String tag : selected_tags ){
result.append(prepend).append(tag);
prepend = "%";
}
String resultString = result.toString();
StringBuilder sb = new StringBuilder();
for (String tag : selected_tags) {
sb.append("%").append(tag);
}
sb.replace(0,1,"tags=");

Categories