hello I am beginner to work with java. I have following code, where I wanted to initialize the string array word[] dynamically consisting of size of total no. of tokens in all documents [] array.
how should I do that?
String []result = {"Shipment of Gold damaged in fire","Delivery of silver arrived in silver truck","shipment of Gold arrived in Truck"};
String []documents = new String[result.length];
for (int k =0; k<result.length; ++k){
documents[k] = result[k].toLowerCase();
System.out.println("document["+k+"] :" + documents[k]);
}
/*step 2: Tokenize all documents and create vocabulary from it*/
int i=0;
String [] word = new String [30]; // how to do dynamic allocation here
int no_of_tokens=0;
for(String document:documents){
StringTokenizer st = new StringTokenizer(document," ");
System.out.print("tokens in document"+ i +":"+ st.countTokens()+"\n");
while(st.hasMoreTokens()) {
word[no_of_tokens]=st.nextToken();
System.out.print(word[no_of_tokens] + "\n");
no_of_tokens++;
}
i++;
}
Either use a List such as ArrayList, or use String.split() instead of StringTokenizer, it will return a String[].
I would use a java.util.ArrayList instead of a static array. You can't resize a static array, but you can create a new, bigger, static array and then copy the initial contents over.
You can use an implementation of the List interface, like ArrayList for this case. It will resize automatically when it almost fills so you don't have to worry about figuring the right initial size.
You use it like this:
....
/*step 2: Tokenize all documents and create vocabulary from it*/
int i=0;
List<String> word = new ArrayList<String>(); // how to do dynamic allocation here
int no_of_tokens=0;
....
while(st.hasMoreTokens()) {
word.add(st.nextToken());
System.out.print(word.get(no_of_tokens) + "\n");
no_of_tokens++;
}
You may use ArrayList<String> or LinkedList<String>. The two differ in the overhead for adding elements (LinkedList is fast, ArrayList is slow) and getting elements via get(i) (LinkedList is slow, ArrayList is fast).
Related
My homework question involves joining strings in a particular sequence. We are first given the strings, followed by a set of instructions that tell us how to concatenate them; finally we print the output string.
I have used the Kattis FastIO class to handle buffered input and output. Below is my algorithm, which iterates through the instructions to concatenate the strings. I have tried making the array of normal strings, StringBuffers and StringBuilders.
The program seems to work as intended, but it gives a time limit error on my submission platform due to inefficiency. It seems like appending the way I did is O(n); is there any faster way?
public class JoinStrings {
public static void main(String[] args) {
Kattio io = new Kattio(System.in, System.out);
ArrayList<StringBuilder> stringList = new ArrayList<StringBuilder>();
int numStrings = io.getInt();
StringBuilder[] stringArray = new StringBuilder[numStrings];
for (int i = 0; i < numStrings; i++) {
String str = io.getWord();
stringArray[i] = new StringBuilder(str);
}
StringBuilder toPrint = stringArray[0];
while (io.hasMoreTokens()) {
int a = io.getInt();
int b = io.getInt();
stringArray[a-1].append(stringArray[b-1]); // this is the line that is done N times
toPrint = stringArray[a-1];
}
io.println(toPrint.toString());
io.flush();
}
}
The StringBuilder.append() copy char from new string to existing string. It's fast but not free.
Instead of keeping appending the String to the StringBuilder array, keep track of the String indexes need to appended. Then finally append the Strings stored in the print out indexes list.
I have a really simple task but I'm a beginner and have no idea how do do it. I have to make a method that will take two parameters: an array of Strings, and a word. We are assuming that the array contains a group of words that are already alphabetized in order. I need to take the word and insert it into the array in the correct alphabetical position, and shift all the previous array elements over accordingly. Here is my code so far but I think it's completely wrong...
public static void insertWordIntoArray(String[] arr, String word){
int i = 0;
while(arr[i].compareTo(word) > 0){i++;}
String temp = ""; String tempV = "";
temp = arr[i];
arr[i] = word;
for (String ind : arr){
i++;
if(i<9)tempV = arr[i+1];
if(i<9)arr[i+1] = temp;
temp = tempV;
}
}
what do you mean by 9? is it the size of the arr? if it is the size, then this will only work if the elements in the array is less then the array size... I think you will find yourself with array out of bound error if elements is same as array size...
array is dynamic...
i think best not to use number such as 9, because this will make the method is not portable...
Can I increase the size of a statically allocated array?
http://en.wikipedia.org/wiki/Dynamic_array
yeah, that's an insertion sort.
You may be better off using a
LinkedList<String>
, you can insert into it without the need to move the elements.
I want to read in a list of words. Then I want alphabetize each of the characters within each word such that I have an entire list of words where each letter is alphabetized. For example if I wanted to read in "cat" "dog" "mouse" from a text file I would have [a,c,t], [d,g,o], and [e,m,o,s,u].
I'm implementing this in Java. I thought about a linked list or some other Collection but I'm not really sure how to implement those with respect to this. I know it's not as simple as converting each string to a char array or using array list. (I already tried those)
Does anyone have any suggestions or examples of doing this?
Basically, I'm just trying to get better with algorithms.
public class AnagramSolver1 {
static List<String> inputList = new ArrayList<String>();
public static void main(String[] args) throws IOException {
List<String> dictionary = new ArrayList<String>();
BufferedReader in = new BufferedReader(new FileReader("src/dictionary.txt"));
String line = null;
Scanner scan = new Scanner(System.in);
while (null!=(line=in.readLine()))
{
dictionary.add(line);
}
in.close();
char[] word;
for (int i = 0; i < dictionary.size(); i++) {
word = inputList.get(i).toCharArray();
System.out.println(word);
}
If you have a String called word, you can obtain a sorted char[] of the characters in word via Arrays.sort
char[] chars = word.toCharArray();
Arrays.sort(chars);
I assume you would want to repeat this process for each member of a collection of words.
If you're interested in knowing what happens behind the scenes here, I would urge you to take a look at the source.
Java provides good support for sorting already: all you need is converting your String to an array of char[], call Arrays.sort on it, and then convert that array back to String.
If you want to have some fun with algorithms, however, you could try going for a linear counting sort: count the letters in the original, then go through the counts in alphabetical order, and write out the count number of characters.
I have a String Array, map[] which looks like...
"####"
"#GB#"
"#BB#"
"####"
So map[1] = "#GB#"
How do I turn this into a 2D array so that newMap[1][1] would give me "G"?
Thanks a lot.
If you really need it, you can use String.toCharArray on each element array to convert them into an array.
String[] origArr = new String[10];
char[][] charArr = new char[10][];
for(int i = 0; i< origArr.length;i++)
charArr[i] = origArr[i].toCharArray();
If you want to break it up into String[] instead, you could use (thanks Pshemo)
String[] abc = "abc".split("(?!^)"); //-> ["a", "b", "c"]
This won't be dynamic. It will take O(n) + m to get to a character of a string. A much faster and dynamic approach would be a Hashmap where the key is the String and the value is a char array. Kind of unnecessarily complex but you get the seeking and individual letter charAts without having to go through the cumbersome process of resizing a primitive array.
I got a one dimensional array of strings in java, in which i want to change all strings to lowercase, to afterwards compare it to the original array so i can have the program check whether there are no uppercase chars in my strings/array.
i've tried using x.toLowercase but that only works on single strings.
Is there a way for me to convert the whole string to lowercase?
Kind regards,
Brand
arraylist.stream().map(s -> s.toLowerCase()).collect(Collectors.toList())
may help you
If you want a short example, you could do the following
String[] array = ...
String asString = Arrays.toString(array);
if(asString.equals(asString.toLowerCase())
// no upper case characters.
String array[]= {"some values"};
String str= String.join(',',array);
String array_uppercase[]=str.toLowerCase().split(',');
Just two line
String[] array = {"One", "Two"};
for(int i=0;i<array.length;i++){
if(!array[i].equals(array[i].toLowerCase()))
System.out.println("It contains uppercase char");
array[i] = array[i].toLowerCase();
}
for(int i=0;i<array.length;i++)
System.out.println(array[i]);
OUTPUT:
It contains uppercase char
It contains uppercase char
one
two
There's no easy way to invoke a method on every element of a collection in Java; you'd need to manually create a new array of the correct size, walk through the elements in your original array and sequentially add their lowercased analogue to the new array.
However, given what you're specifically trying to do, you don't need to compare the whole array at once to do this, and incur the cost of copying everything. You can simply iterate through the array - if you find an element which is not equal to its lowercase version, you can return false. If you reach the end of the array without finding any such element, you can return true.
This would in fact be more efficient, since:
you get to short-circuit further evaluation if you find an element that does have uppercase characters. (Imagine the case where the first element of a million-string array has an uppercase; you've just saved on a million calls to lowercase()).
You don't have to allocate memory for the whole extra array that you won't be using beyond the comparison.
Even in the best case scenario, your proposed scenario would involve one iteration through the array to get the lowercase versions, then another iteration through the array to implement the equals. Doing both in a single iteration is likely to be more efficient even without the possibility of short-circuiting.
Previously we used (In Java < 8)
String[] x = {"APPLe", "BaLL", "CaT"};
for (int i = 0; i < x.length; i++) {
x[i] = x[i].toLowerCase();
}
Now in Java8 :
x= Arrays.asList(x).stream().map(String::toLowerCase).toArray(String[]::new);
Two steps are needed:
Iterate over the array of Strings
Convert each one to lower case.
you can convert the array of strings to single string and then convert it into lower case and please follow the sample code below
public class Test {
public static void main(String[] args) {
String s[]={"firsT ","seCond ","THird "};
String str = " ";
for (int i = 0; i < s.length; i++) {
str = str + s[i];
}
System.out.println(str.toLowerCase());
}
}
import java.util.*;
public class WhatEver {
public static void main(String[] args) {
List <String> list = new ArrayList();
String[] x = {"APPLe", "BaLL", "CaT"};
for (String a : x) {
list.add(a.toLowerCase);
}
x = list.toArray(new String[list.size()]);
}
}
The following code may help you
package stringtoupercasearray;
import java.util.Scanner;
/**
*
* #author ROBI
*/
public class StringToUperCaseArray {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int size;
String result = null;
System.out.println("Please enter the size of the array: ");
Scanner r=new Scanner(System.in);
size=r.nextInt();
String[] s=new String[size];
System.out.println("Please enter the sritngs:");
for(int i=0;i<s.length;i++){
s[i]=r.next();
}
System.out.print("The given sritngs are:");
for (String item : s) {
//s[i]=r.nextLine();
System.out.print(item+"\n");
}
System.out.println("After converting to uppercase the string is:");
for (String item : s) {
result = item.toUpperCase();
System.out.println(result);
}
}
}
You can do it with a single line of code. Just copy and paste the following snippet, without any looping at all.
String[] strArray = {"item1 Iteme1.1", "item2", "item3", "item4", "etc"}//This line is not part of the single line (=D).
String strArrayLowerCase[] = Arrays.toString(strArray).substring(1)
.replace("]", "").toLowerCase().split(",");
Happy String Life. =D