so I'm pretty new at Java and StackOverflow (That's what they all say) and I am stuck at the given problem:
My method is given a String e.g.: "[ 25 , 25 , 125 , 125]". Now the method should return an Array of integers representation of the String provided, that is: it should return
[25,25,125,125].
Here is a segment of my method. Note: input is the String provided
if(input.charAt(index) == '['){
index++;
int start = index;
while(index <= input.length() && input.charAt(index) != ']'){
index++;
}
String[] arrayStr = input.substring(start, index).split(",");
int[] arrayInt = new int[4];
for (int i = 0; i < arrayStr.length; i++){
arrayInt[i] = Integer.parseInt(arrayStr[i]);
}
return arrayInt;
My code works if input is: "[25,25,125,125]" (If there are no spaces between the numbers).
However if there are spaces between the numbers then my code doesn't work and I understand why, but I am struggling to find a way to solve this problem. Any help will be appreciated.
Spaces will fail with Integer.parseInt(arrayStr[i]) (e.g. the string "25 " is not a valid number as it contains a space. (parseInt will throw an exception in such cases.)
However you can solve it quickly by trimming your array elements:
Integer.parseInt(arrayStr[i].trim())
trim() returns a copy of the string without leading/trailing white space
You can replace the space with empty in the string
input=input.replace(" ","")
You can
remove [ and ] and all spaces
split on , to get all tokens
iterate over all tokens
parse string number to int
add parsed int to result array
So your code can look like
String data = "[ 25 , 25 , 125 , 125]";
String[] tokens = data.replaceAll("\\[|\\]|\\s", "").split(",");
int[] array = new int[tokens.length];
for (int i=0; i<tokens.length; i++){
array[i]=Integer.parseInt(tokens[i]);
}
Or if you have Java 8 you can use streams like
int[] array = Stream.of(data.replaceAll("\\[|\\]|\\s", "").split(","))
.mapToInt(number -> Integer.parseInt(number))
.toArray();
Related
I have a task which involves me creating a program that reads text from a text file, and from that produces a word count, and lists the occurrence of each word used in the file. I managed to remove punctuation from the word count but I'm really stumped on this:
I want java to see this string "hello-funny-world" as 3 separate strings and store them in my array list, this is what I have so far , with this section of code I having issues , I just get "hello funny world" seen as one string:
while (reader.hasNext()){
String nextword2 = reader.next();
String nextWord3 = nextword2.replaceAll("[^a-zA-Z0-9'-]", "");
String nextWord = nextWord3.replace("-", " ");
int apcount = 0;
for (int i = 0; i < nextWord.length(); i++){
if (nextWord.charAt(i)== 39){
apcount++;
}
}
int i = nextWord.length() - apcount;
if (wordlist.contains(nextWord)){
int index = wordlist.indexOf(nextWord);
count.set(index, count.get(index) + 1);
}
else{
wordlist.add(nextWord);
count.add(1);
if (i / 2 * 2 == i){
wordlisteven.add(nextWord);
}
else{
wordlistodd.add(nextWord);
}
}
This can work for you ....
List<String> items = Arrays.asList("hello-funny-world".split("-"));
By considering that you are using the separator as '-'
I would suggest you to use simple split() of java
String name="this-is-string";
String arr[]=name.split("-");
System.out.println("Here " +arr.length);
Also you will be able to iterate through this array using for() loop
Hope this helps.
I want to return words from a String array one after the other.
public String CurrentString(int move) {
int currentString = 0;
EditText ed = (EditText) findViewById(R.id.ed);
String[] strings = ed.getText().toString().split(" ");
int newString = currentString move;
if (newString >= strings.length) {
// if the new position is past the end of the array, go back to the beginning
newString = 0;
}
if (newString < 0) {
// if the new position is before the beginning, loop to the end
newString = strings.length - 1;
}
currentString = newString;
Toast.makeText(getApplicationContext(), strings[currentString],Toast.LENGTH_LONG).show();
return strings[currentString];
}
The problem is that my above code doesn't return all texts. Please, help.
Seems you have not done enough "homework" and are having problems with arrays, (that's why people are down-voting [this is not a site for beginners who not do put in the required "research effort", the site would be inundated]).
The current trend is to downvote AND/OR leave a sarcastic comment ;O)
Also your code contains errors that will not compile, so you have not even bothered to test it ! ;O(
Lucky for you you cannot get a negative reputation !
Seriously please do some research (google it !)
Here is some code that may help. Use split to process your string into a string array:
String string = "I want a string array of all these words";//input string
// ^ ^ ^ ^ ^ ^ ^ ^ ^
// 0 1 2 3 4 5 6 7 8 //index
String[] array_of_words;//output array of words
array_of_words = CurrentString(string);//execute method
Log.i("testing", array_of_words[8]);//this would be "words" in this example
//later you might want to process commas and full stops etc...
public String[] CurrentString(String string)
{
String[] array = string.split(" "); //use space to split string into words
//With the advent of Java 5, we can make our for loops a little cleaner and easier to read
for ( String sarray : array ) //loop through String array
{
Log.i("CurrentString", sarray );//print the words
}
return array ;//return String array
}
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);
hello every one i got a string from csv file like this
LECT-3A,instr01,Instructor 01,teacher,instr1#learnet.com,,,,male,phone,,
how to split this string with comma i want the array like this
s[0]=LECT-3A,s[1]=instr01,s[2]=Instructor 01,s[3]=teacher,s[4]=instr1#learnet.com,s[5]=,s[6]=,s[7]=,s[8]=male,s[9]=phone,s[10]=,s[11]=
can anyone please help me how to split the above string as my array
thank u inadvance
- Use the split() function with , as delimeter to do this.
Eg:
String s = "Hello,this,is,vivek";
String[] arr = s.split(",");
you can use the limit parameter to do this:
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
Example:
String[]
ls_test = "LECT-3A,instr01,Instructor 01,teacher,instr1#learnet.com,,,,male,phone,,".split(",",12);
int cont = 0;
for (String ls_pieces : ls_test)
System.out.println("s["+(cont++)+"]"+ls_pieces);
output:
s[0]LECT-3A
s[1]instr01
s[2]Instructor 01
s[3]teacher
s[4]instr1#learnet.com
s[5]
s[6]
s[7]
s[8]male
s[9]phone
s[10]
s[11]
You could try something like so:
String str = "LECT-3A,instr01,Instructor 01,teacher,instr1#learnet.com,,,,male,phone,,";
List<String> words = new ArrayList<String>();
int current = 0;
int previous = 0;
while((current = str.indexOf(",", previous)) != -1)
{
words.add(str.substring(previous, current));
previous = current + 1;
}
String[] w = words.toArray(new String[words.size()]);
for(String section : w)
{
System.out.println(section);
}
This yields:
LECT-3A
instr01
Instructor 01
teacher
instr1#learnet.com
male
phone
I'm a novice with Java. I took a class in C, so I'm trying to get myself out of that mode of thinking. The program I'm writing has a section in which the user enters an integer, n, and then n number of words afterwards. This section then searches through those words and finds the shortest one, then returns it to the user. For instance, an input might be:
INPUT: 4 JAVA PROGRAMMING IS FUN
OUTPUT: IS
The code I have currently seems to return the wrong word. In this instance, it returns "PROGRAMMING", when it should return "IS". I thought maybe you all could point me in the right direction.
int numwords = scan.nextInt();
String sentence = scan.nextLine();
String shortestword = new String();
String[] words = sentence.split(" ");
for (int i = 0; i < numwords; i++){
if (shortestword.length() < words[i].length()){
shortestword = words[i];
}
}
System.out.printf(shortestword);
To give you an idea of what I was trying to do, I was attempting to enter the words into a string, "sentence," then break that string up into individual words in an array, "words[]," then run a for loop to compare the strings to each other by comparing the lengths to the entries in the array. Thank you for your assistance!
You're almost there, but your comparison to detect the shortest word is reversed. It should be:
if (words[i].length() < shortestword.length()) {
That is, if your current word's length is less than the length of your previous shortest word, overwrite it.
Also, instead of starting with an empty String, start with the first word, i.e., words[0]. Otherwise, the empty string will always be shorter than any string in your array:
String[] words = sentence.split(" ");
String shortestword = words[0];
for (int i = 1; i < numwords; i++) { // start with 1, because you already have words[0]
Your if statement is wrong. This should work.
int numwords = scan.nextInt();
String sentence = scan.nextLine();
String shortestword = new String();
String[] words = sentence.split(" ");
for (int i = 0; i < numwords; i++){
if (shortestword.length() > words[i].length()){
shortestword = words[i];
}
}
System.out.printf(shortestword);
Here's a version that makes use of Java 8's Stream API:
String sentence = "PROGRAMMING IS FUN";
List<String> words = Arrays.asList(sentence.split(" "));
String shortestWord = words.stream().min(
Comparator.comparing(
word -> word.length()))
.get();
System.out.println(shortestWord);
You can also sort more complex objects by any of their attribute: If you have a couple of Persons and you wanted to sort them by their lastName, shortest first, the code becomes:
Person personWithShortestName = persons.stream().min(
Comparator.comparing(
person -> person.lastName.length()))
.get();
Java 8 has made it simpler. Convert your String array to a list and use sorted() to compare and sort your list in ascending order. Finally, use findFirst() to get the first value of your list (which is shortest after sorting).
have a look,
String[] words = new String[]{"Hello", "name", "is", "Bob"};
String shortest = Arrays.asList(words).stream()
.sorted((e2, e1) -> e1.length() > e2.length() ? -1 : 1)
.findFirst().get();
System.out.println(shortest);