Create a char array for every string inside a string array - java

I'm trying to implement in java this little project: I want to rename the episodes of an entire season in a series using a text file that has the names of all the episodes in that season.
To that end I wrote a code that reads the text file and stores every line of text (the name of an episode) as a string array, where every element of the array stores the name of one episode. Also, I wrote a code that takes the FIRST element of that array (an array called arrayLines[]) and renames a given file.
This code works like a charm.
What I want to do next is to create a char array for every element in the string array arrLines[].
The pseudo-code i'm thinking to implement is something like this:
for(int i=0; i<arrLines.length; i++){
char line_i+1[] = arrLines[i];
}
and thus getting many arrays with the names line_1, line_2,..., line_arrLines.length, with the name of every episode stored as a char array.
How can I implement something like this?

Just use a 2-dimensional char array:
char[][] lines = new char[arrLines.length][];
for (int i = 0; i < arrLines.length; i++) {
lines[i] = arrLines[i].toCharArray();
}
If you have Java 8, you can use Streams:
char[][] lines = Arrays.stream(arrLines)
.map(String::toCharArray)
.toArray(char[][]::new);

You can use the String toCharArra method.
for(int i = 0; i < strArray.length; i++) {
char[] charArray = strArray[i].toCharArray();
}

Related

How can I convert a Jsoup Document[] array to a String[]?

My question is the same as this one except that instead of a single Document I have an array (Document[]).
I normally use R, not Java, so I apologize if it should be apparent how to change the solution from the linked thread for the case of an array.
The solution for the case of a single Document object was:
String htmlString = doc.html();
My code to create the object was:
Document[] target = new Document[20];
for(int n=0; n < strvec.length;n++){
target[n] = Jsoup.connect(strvec[n]).get();
}
I tried a few things like creating the original target object as String[], putting .toString() on the end of Jsoup.connect(strvec[n]).get() and elsewhere, but these attempts were unsucessful.
it is assumed that serves is an array of String containing the URL to connect, you do not need to create another array of Document
String[] result = new String[strvec.length];
for(int n=0; n < strvec.length;n++)
result[n]=Jsoup.connect(strvec[n]).get().html();
String[] htmlList = new String[target.length];
for(int i = 0; i < target.length; i++)
htmlList[i] = target[i].html();
This loop should do what you want.

Java:Why is this not possible?

String myName[] = {"Mouse","Laptop","Facebook","Logitech"};
// print the first character
System.out.println(myName.charAt(0));
// print the second character
System.out.println(myName.charAt(1));
// print the last character
int lastPos = myName.length() - 1;
System.out.println(myName.charAt( lastPos ));
/*any one can explain to this noob? It's telling me to change to length, but that's not what I want. Basically what I want is to go through each character of string. */
You are using String methods on an array. To access the characters in the strings, you need to first get one of the String objects sitting in that array. Doing myName[0].charAt(0) for example will give you the first character of the first String in the array. If your intention is to do something with each character in each string in the array, you should use a loop like so:
for (int i=0; i<myName.length; i++){
for (int j=0; j< myName[i].length(); j++){
myName[i].charAt(j); // Do something with ths value, I am just getting it here.
}
}
You have created an Array of Strings where each element in that array is a "String". So, you can't use charAt to the array.
charAt(index) by it's name - you can think (give me the character at position index).
So, first you need to go to the particular "String" and then say "give me the character at position 'x' ".
So, if you want to go to "Facebook", then say hey "give me the element of the array at position 3 which is index 2" using:
myName[2];
store it in say variable str which needs to be a "String" :
String str = myName[2];
Then, you can use charAt(x) on str using :
for(int i =0 ; i<str.length() ; i++){
System.out.println(str.charAt(i));
}
You have initialized an array of string.Later if u want to access them you cannot directly use myName simply. Because its a container which has many memory locations in which data is stored. So by just using myName is not possible instead it should be followed by its index (ie, myName[i] pass 0,1,2.. in place of i). See the modification of ur program below. May be u can understand it.
public class ArrayDemo {
public static void main(String[] args) {
String myName[] = {"Mouse","Laptop","Facebook","Logitech"};
for(int i=0;i<=myName.length()-1;i++){
// print the first character
System.out.println(myName[i].charAt(0));
// print the second character
System.out.println(myName[i].charAt(1));
// print the last character
int lastPos = myName[0].length() - 1;
System.out.println(myName[i].charAt(lastPos));
}
}
}

multiply string element per int element from two arrays Java

I am learning Java and looking for a comprehensive code of multiplying the elements from 2 arrays, possibly without importing anything to achieve it.
In Python it's quite easy:
a=['a','b','c','d']
b=[1,2,3,4]
[x*y for x,y in zip(a,b)]
['a', 'bb', 'ccc', 'dddd']
How can I achieve the same thing in Java, when the first array is an array of strings and the second is integers?
I'm afraid Java isn't going to support this kind of thing natively, and you'll need to perform some of your own logic to implement it. Let's say you've got your String[]..
String[] a = {"a", "b", "c", "d"};
And you've got your int[]..
int[] b = {1,2,3,4};
Next, you'll need to check that the arrays are the same size.
if(a.length == b.length) {
// Continue.
}
Then you need to implement a loop, to go through each item in the arrays.
for(int x = 0; x < a.length; x++)
{
// Some looping code.
}
And you're going to grab each item.
String value = a[x];
int multiplier = b[x];
If you're not importing anything, you declare the total value:
String total = "";
But if you're allowing for a StringBuilder, then you'll import it and declare..
StringBuilder total = new StringBuilder();
NOTE: StringBuilder is strongly recommended here.
And then you're looping multiplier amount of times..
for(int y = 0; y < multiplier; y++)
{
// If you use StringBuilder..
total.append(value);
// If you don't..
total += value;
}
// If you use StringBuilder..
a[x] = total.toString();
// If you don't...
a[x] = total;
This will set the value of a[x] to the repeated String.
NOTE: Something that's also important is leaning good practise. If you're using Java code, it's considered terrible practise to repeatedly concatenate String objects. StringBuilder is more efficient, and is the Java standard. I would strongly recommend using this.
Have fun putting it all together!!
To create string filled with multiple instances of same character like "ccc" you can firs create array of characters which will hold only 3 characters like
char[] myCharacters = new char[3];
Now this array is filled with zeroes ('\0'), so you need to fill it with desired character 'c'. You simply do it using for loop
for (int i = 0; i<myCharacters; i++){
myCharacters[i] = 'c';
}
After this your array will contain ['c', 'c', 'c'].
Now you can use this array to create string using characters from it. To do so you just need to pass this array to String constructor like
String myString = new String(myCharacters);
And there you go. Now you have "ccc" String. Repeat these steps for each pair of elements from a and b arrays.
You can also use shorter version which kinds of do the same
String myString = new String(new char[3]).replace('\0','c');//will produce "ccc"

Parsing a String [] of csv's

I am trying to take the info from a string array that each string in the array is a csv, like so:
String[] jobs = {
"2,-8,4",
"10,-10,9,-3",
"9,-1"
}
I know how to take csv from a file, but i dont understand how to take these values from the string and get their int forms amd put them into an array. I was thinking i can all just put them in 1 array.
All you really need to do is split the strings and parse to int.
List<Integer> ints = new ArrayList<Integer>();
// For each element in jobs array
for (int i = 0; i < jobs.length; i++)
// For each csv in current element
for (String s : jobs[i].split(","))
ints.add(Integer.parseInt(s)); // parse and add to ints
for (int i : ints)
System.out.println(i);

Determining if a given string of words has words greater than 5 letters long

So, I'm in need of help on my homework assignment. Here's the question:
Write a static method, getBigWords, that gets a String parameter and returns an array whose elements are the words in the parameter that contain more than 5 letters. (A word is defined as a contiguous sequence of letters.) So, given a String like "There are 87,000,000 people in Canada", getBigWords would return an array of two elements, "people" and "Canada".
What I have so far:
public static getBigWords(String sentence)
{
String[] a = new String;
String[] split = sentence.split("\\s");
for(int i = 0; i < split.length; i++)
{
if(split[i].length => 5)
{
a.add(split[i]);
}
}
return a;
}
I don't want an answer, just a means to guide me in the right direction. I'm a novice at programming, so it's difficult for me to figure out what exactly I'm doing wrong.
EDIT:
I've now modified my method to:
public static String[] getBigWords(String sentence)
{
ArrayList<String> result = new ArrayList<String>();
String[] split = sentence.split("\\s+");
for(int i = 0; i < split.length; i++)
{
if(split[i].length() > 5)
{
if(split[i].matches("[a-zA-Z]+"))
{
result.add(split[i]);
}
}
}
return result.toArray(new String[0]);
}
It prints out the results I want, but the online software I use to turn in the assignment, still says I'm doing something wrong. More specifically, it states:
Edith de Stance states:
⇒     You might want to use: +=
⇒     You might want to use: ==
⇒     You might want to use: +
not really sure what that means....
The main problem is that you can't have an array that makes itself bigger as you add elements.
You have 2 options:
ArrayList (basically a variable-length array).
Make an array guaranteed to be bigger.
Also, some notes:
The definition of an array needs to look like:
int size = ...; // V- note the square brackets here
String[] a = new String[size];
Arrays don't have an add method, you need to keep track of the index yourself.
You're currently only splitting on spaces, so 87,000,000 will also match. You could validate the string manually to ensure it consists of only letters.
It's >=, not =>.
I believe the function needs to return an array:
public static String[] getBigWords(String sentence)
It actually needs to return something:
return result.toArray(new String[0]);
rather than
return null;
The "You might want to use" suggestions points to that you might have to process the array character by character.
First, try and print out all the elements in your split array. Remember, you do only want you look at words. So, examine if this is the case by printing out each element of the split array inside your for loop. (I'm suspecting you will get a false positive at the moment)
Also, you need to revisit your books on arrays in Java. You can not dynamically add elements to an array. So, you will need a different data structure to be able to use an add() method. An ArrayList of Strings would help you here.
split your string on bases of white space, it will return an array. You can check the length of each word by iterating on that array.
you can split string though this way myString.split("\\s+");
Try this...
public static String[] getBigWords(String sentence)
{
java.util.ArrayList<String> result = new java.util.ArrayList<String>();
String[] split = sentence.split("\\s+");
for(int i = 0; i < split.length; i++)
{
if(split[i].length() > 5)
{
if(split[i].matches("[a-zA-Z]+"))
{
result.add(split[i]);
}
if (split[i].matches("[a-zA-Z]+,"))
{
String temp = "";
for(int j = 0; j < split[i].length(); j++)
{
if((split[i].charAt(j))!=((char)','))
{
temp += split[i].charAt(j);
//System.out.print(split[i].charAt(j) + "|");
}
}
result.add(temp);
}
}
}
return result.toArray(new String[0]);
}
Whet you have done is correct but you can't you add method in array. You should set like a[position]= spilt[i]; if you want to ignore number then check by Float.isNumber() method.
Your logic is valid, but you have some syntax issues. If you are not using an IDE like Eclipse that shows you syntax errors, try commenting out lines to pinpoint which ones are syntactically incorrect. I want to also tell you that once an array is created its length cannot change. Hopefully that sets you off in the right directions.
Apart from syntax errors at String array declaration should be like new String[n]
and add method will not be there in Array hence you should use like
a[i] = split[i];
You need to add another condition along with length condition to check that the given word have all letters this can be done in 2 ways
first way is to use Character.isLetter() method and second way is create regular expression
to check string have only letter. google it for regular expression and use matcher to match like the below
Pattern pattern=Pattern.compile();
Matcher matcher=pattern.matcher();
Final point is use another counter (let say j=0) to store output values and increment this counter as and when you store string in the array.
a[j++] = split[i];
I would use a string tokenizer (string tokenizer class in java)
Iterate through each entry and if the string length is more than 4 (or whatever you need) add to the array you are returning.
You said no code, so... (This is like 5 lines of code)

Categories