Using the Split() method in Java - java

I am trying to split an input like the following:
0-0-1-0;Wolf Blitzer;leaf
with the following code:
public static void buildTree(String treeFile){
//temp string array to hold the input as 3 seperate Strings, seperated by ;
String[] temp= new String[3];
int i=0;
//will split the string into its 3 parts
for (String newTemp: treeFile.split(";")) {
temp[i]=newTemp;
i++;
}
//can hold up to 100 char, each describing a path
char[] pathArray= new char[100];
int pathCursor=0;
i=0;
//once again split the first part of the string, which holds the path, into an array of chars,
//parse each String into a char and then set equal to in array in array
for(String newTemp: temp[0].split("-")){
char c=newTemp.charAt(0);
pathArray[i]=c;
i++;
pathCursor++;
}
for(int j=0; j<3;j++){
System.out.println(temp[j]);
}
for(int j=0; j<pathCursor;j++){
System.out.println(pathArray[j]);
}
}
When I encounter spaces such as the the space in Wolf Blitzer, or periods in titles such as Dr. Strange, my split function doesn't work correctly. I thought that it would only split at whatever character I defined (in this case the ; and later the -). Am I not understanding split() correctly?
EDIT:
My expected output should be:
0-0-1-0
Wolf Blitzer
Leaf
0
0
1
0
Also I am trying to diagnose the issue and therefore am manually passing in the TreeFile with a simple test file which just asks for a string and then calls the method

Related

Writing method that spells word backwords and identifies number of palindromes

I'm new to java and I wrote this method to input a string word and output the word spelled backwards. The intent is to create a method and not use an already existing method such as the simple reverse. Please help point me in the direction of how to do this to reverse a word. I'm also trying to determine/count if there are palindromes. Please help! I've read other questions and I can't find anything specific enough to my case. I know that my code doesn't run, though I'm unsure how to fix it to get the correct output.
An example would be the word "backwards" to go to "sdrawkcab".
public static int reverseWord(String word) {
int palindromes = 0;
for (int i = word.length(); i >= 0; i--) {
System.out.print(i);
word.equalsIgnoreCase();
if (word.charAt(i)) == index(word.charAt(0 && 1))) {
palindromes++
System.out.println(palindromes)
}
return i;
}
}
There are multiple problems with your code.
1.The prototype of equalsIgnoreCase is
public boolean equalsIgnoreCase(String str);
So this method expect a String to be passed,but your not not passing anything here.To fix this,pass another string with whom you want to match your word like this..
word.equalsIgnoreCase("myAnotherString");
2.word.charAt(i);
Suppose word="qwerty",so indexing of each character will be like this
/* q w e r t y
0 1 2 3 4 5 */
So when you use i = word.length();i will 6 since word is of length 6.So
word.charAt(i) will search for character at index 6,but since there is not index 6,it will return an exception ArrayIndexOutOfBound.To fix this,start i from word.length()-1.
3.if (word.charAt(i));
This extra " ) ".Remove it.
Is Index() your own method?.If Yes,then check that also.
the below code prints the reverse of the input string and checks if it is a palindrome
public static void main(String[] args) {
String input = "dad";
char temp[] = input.toCharArray();//converting it to a array so that each character can be compared to the original string
char output[] = new char[temp.length];//taking another array of the same size as the input string
for (int i = temp.length - 1, j = 0; i >= 0; i--, j++) {//i variable for iterating through the input string and j variable for inserting data into output string.
System.out.print(temp[i]);//printing each variable of the input string in reverse order.
output[j] = temp[i];//inserting data into output string
}
System.out.println(String.valueOf(output));
if (String.valueOf(output).equalsIgnoreCase(input)) {//comparing the output string with the input string for palindrome check
System.out.println("palindrome");
}
}
Because your question about what is wrong with your code was already answered here is another way you could do it by using some concepts which are somewhat less low level than directly working with character arrays
public static boolean printWordAndCheckIfPalindrome(final String word) {
// Create a StringBuilder which helps when building a string
final StringBuilder reversedWordBuilder = new StringBuilder("");
// Get a stream of the character values of the word
word.chars()
// Add each character to the beginning of the reversed word,
// example for "backwards": "b", "ab", "cab", "kcab", ...
.forEach(characterOfString -> reversedWordBuilder.insert(0, (char) characterOfString));
// Generate a String out of the contents of the StringBuilder
final String reversedWord = reversedWordBuilder.toString();
// print the reversed word
System.out.println(reversedWord);
// if the reversed word equals the given word it is a palindrome
return word.equals(reversedWord);
}

Remove chars from string in Java from file

How would I remove the chars from the data in this file so I could sum up the numbers?
Alice Jones,80,90,100,95,75,85,90,100,90,92
Bob Manfred,98,89,87,89,9,98,7,89,98,78
I want to do this so for every line it will remove all the chars but not ints.
The following code might be useful to you, try running it once,
public static void main(String ar[])
{
String s = "kasdkasd,1,2,3,4,5,6,7,8,9,10";
int sum=0;
String[] spl = s.split(",");
for(int i=0;i<spl.length;i++)
{
try{
int x = Integer.parseInt(spl[i]);
sum = sum + x;
}
catch(NumberFormatException e)
{
System.out.println("error parsing "+spl[i]);
System.out.println("\n the stack of the exception");
e.printStackTrace();
System.out.println("\n");
}
}
System.out.println("The sum of the numbers in the string : "+ sum);
}
even the String of the form "abcd,1,2,3,asdas,12,34,asd" would give you sum of the numbers
You need to split each line into a String array and parse the numbers starting from index 1
String[] arr = line.split(",");
for(int i = 1; i < arr.length; i++) {
int n = Integer.parseInt(arr[i]);
...
try this:
String input = "Name,2,1,3,4,5,10,100";
String[] strings = input.split(",");
int result=0;
for (int i = 1; i < strings.length; i++)
{
result += Integer.parseInt(strings[i]);
}
You can make use of the split method of course, supplying "," as the parameter, but that's not all.
The trick is to put each text file's line into an ArrayList. Once you have that, move forwars the Pseudocode:
1) Put each line of the text file inside an ArrayList
2) For each line, Split to an array by using ","
3) If the Array's size is bigger than 1, it means there are numbers to be summed up, else only the name lies on the array and you should continue to the next line
4) So the size is bigger than 1, iterate thru the strings inside this String[] array generated by the Split function, from 1 to < Size (this will exclude the name string itself)
5) use Integer.parseInt( iterated number as String ) and sum it up
There you go
Number Format Exception would occur if the string is not a number but you are putting each line into an ArrayList and excluding the name so there should be no problem :)
Well, if you know that it's a CSV file, in this exact format, you could read the line, execute string.split(',') and then disregard the first returned string in the array of results. See Evgenly's answer.
Edit: here's the complete program:
class Foo {
static String input = "Name,2,1,3,4,5,10,100";
public static void main(String[] args) {
String[] strings = input.split(",");
int result=0;
for (int i = 1; i < strings.length; i++)
{
result += Integer.parseInt(strings[i]);
}
System.out.println(result);
}
}
(wow, I never wrote a program before that didn't import anything.)
And here's the output:
125
If you're not interesting in parsing the file, but just want to remove the first field; then split it, disregard the first field, and then rejoin the remaining fields.
String[] fields = line.split(',');
StringBuilder sb = new StringBuilder(fields[1]);
for (int i=2; i < fields.length; ++i)
sb.append(',').append(fields[i]);
line = sb.toString();
You could also use a Pattern (regular expression):
line = line.replaceFirst("[^,]*,", "");
Of course, this assumes that the first field contains no commas. If it does, things get more complicated. I assume the commas are escaped somehow.
There are a couple of CsvReader/Writers that might me helpful to you for handling CSV data. Apart from that:
I'm not sure if you are summing up rows? columns? both? in any case create an array of the target sum counters int[] sums(or just one int sum)
Read one row, then process it either using split(a bit heavy, but clear) or by parsing the line into numbers yourself (likely to generate less garbage and work faster).
Add numbers to counters
Continue until end of file
Loading the whole file before starting to process is a not a good idea as you are doing 2 bad things:
Stuffing the file into memory, if it's a large file you'll run out of memory (very bad)
Iterating over the data 2 times instead of one (probably not the end of the world)
Suppose, format of the string is fixed.
String s = "Alice Jones,80,90,100,95,75,85,90,100,90,92";
At first, I would get rid of characters
Matcher matcher = Pattern.compile("(\\d+,)+\\d+").matcher(s);
int sum = 0;
After getting string of integers, separated by a comma, I would split them into array of Strings, parse it into integer value and sum ints:
if (matcher.find()){
for (String ele: matcher.group(0).split(",")){
sum+= Integer.parseInt(ele);
}
}
System.out.println(sum);

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)

Java character array initializer

I tried to make a program that separates characters.
The question is:
"Create a char array and use an array initializer to initialize the array with the characters in the string 'Hi there'. Display the contents of the array using a for-statement. Separate each character in the array with a space".
The program I made:
String ini = "Hi there";
char[] array = new char[ini.length()];
for(int count=0;count<array.length;count++) {
System.out.print(" "+array[count]);
}
What should I do to fix this problem?
Here's how you convert a String to a char array:
String str = "someString";
char[] charArray = str.toCharArray();
I'd recommend that you use an IDE when programming, to easily see which methods a class contains (in this case you'd be able to find toCharArray()) and compile errors like the one you have above. You should also familiarize yourself with the documentation, which in this case would be this String documentation.
Also, always post which compile errors you're getting. In this case it was easy to spot, but when it isn't you won't be able to get any answers if you don't include it in the post.
you are doing it wrong, you have first split the string using space as a delimiter using String.split() and populate the char array with charcters.
or even simpler just use String.charAt() in the loop to populate array like below:
String ini="Hi there";
char[] array=new char[ini.length()];
for(int count=0;count<array.length;count++){
array[count] = ini.charAt(count);
System.out.print(" "+array[count]);
}
or one liner would be
String ini="Hi there";
char[] array=ini.toCharArray();
char array[] = new String("Hi there").toCharArray();
for(char c : array)
System.out.print(c + " ");
Here is the code
String str = "Hi There";
char[] arr = str.toCharArray();
for(int i=0;i<arr.length;i++)
System.out.print(" "+arr[i]);
Instead of above way u can achieve the solution simply by following method..
public static void main(String args[]) {
String ini = "Hi there";
for (int i = 0; i < ini.length(); i++) {
System.out.print(" " + ini.charAt(i));
}
}
You initialized and declared your String to "Hi there", initialized your char[] array with the correct size, and you began a loop over the length of the array which prints an empty string combined with a given element being looked at in the array. At which point did you factor in the functionality to put in the characters from the String into the array?
When you attempt to print each element in the array, you print an empty String, since you're adding 'nothing' to an empty String, and since there was no functionality to add in the characters from the input String to the array. You have everything around it correctly implemented, though. This is the code that should go after you initialize the array, but before the for-loop that iterates over the array to print out the elements.
for (int count = 0; count < ini.length(); count++) {
array[count] = ini.charAt(count);
}
It would be more efficient to just combine the for-loops to print each character out right after you put it into the array.
for (int count = 0; count < ini.length(); count++) {
array[count] = ini.charAt(count);
System.out.println(array[count]);
}
At this point, you're probably wondering why even put it in a char[] when I can just print them using the reference to the String object ini itself.
String ini = "Hi there";
for (int count = 0; count < ini.length(); count++) {
System.out.println(ini.charAt(count));
}
Definitely read about Java Strings. They're fascinating and work pretty well, in my opinion. Here's a decent link: https://www.javatpoint.com/java-string
String ini = "Hi there"; // stored in String constant pool
is stored differently in memory than
String ini = new String("Hi there"); // stored in heap memory and String constant pool
, which is stored differently than
char[] inichar = new char[]{"H", "i", " ", "t", "h", "e", "r", "e"};
String ini = new String(inichar); // converts from char array to string
.
Another easy way is that you use string literal and convert it to charArray in declaration itself.
Something like this -
char array[] = "Hi there".toCharArray();
//Print with white spaces
for(char c : array)
System.out.print(c + " ");

when using a array of strings in java, convert it to lowercase

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

Categories