4

I have a string (taken from file):

Computer: intel, graphic card: Nvidia,

Mouse: razer, color: white etc.

I need to take words between ":" and ",".

When I'm doing this in that way

Scanner sc = new Scanner(new File(path));
    String str = sc.nextLine();

    ArrayList<String> list = new ArrayList<String>();

    while (sc.hasNextLine()) {

        for (int i = 0; i < str.length(); i++) {
            list.add(str.substring(str.indexOf(":"), str.indexOf(",")));
        }
        System.out.println("test");

        sc.nextLine();

    }

I'm only taking ": intel". I don't know how to take more word from same line and them word from next line.

Iothin
  • 53
  • 4
  • `sc.nextLine();` what do you expect this to do on its own? – Federico klez Culloca Feb 21 '20 at 11:53
  • I would re-examine *parsing a file line by line in java*. If you don't assign `sc.nextLine()` to anything - you're essentially tossing the value. – sleepToken Feb 21 '20 at 11:54
  • you can use `split` method twice for that, once you split with `:` and from array which you have after first split you are doing second `split` by `,` and the you have arrays with words which you want. I know my idea is not the best but just want give and Idea what you can use. – noname Feb 21 '20 at 11:54
  • @FedericoklezCulloca I was trying with this and this doesnt give me any proper result. I forgot to delete this here. – Iothin Feb 21 '20 at 12:21
  • @Iothin , what is your exact expected output?? – Vishwa Ratna Feb 21 '20 at 12:39
  • @VishwaRatna ": intel" and only this one word. – Iothin Feb 21 '20 at 12:50

6 Answers6

1

You are facing this problem because the indexof() function returns the first occurrence of that character in the string. Hence you you are getting the substring between the first occurrence of ':' and first occurrence of ',' . To solve your problem use the functions FirstIndexOf() and LastIndexOf() with str.substring instead of the function IndexOf(). This will return the substring between the first occurrence of ':' and the last occurrence of ',' . I hope you find this answer helpful.

Alok
  • 39
  • 7
1

Assuming the content of the file, test.txt is as follows:

Computer: intel, graphic card: Nvidia
Mouse: razer, color: white

The following program will

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

class Coddersclub {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner sc = new Scanner(new File("test.txt"));
        ArrayList<String> list = new ArrayList<String>();
        String str = "";
        while (sc.hasNextLine()) {
            str = sc.nextLine();
            String[] specs = str.split(",");
            for (String item : specs) {
                list.add(item.substring(item.indexOf(":") + 1).trim());
            }
        }
        System.out.println(list);
    }
}

output:

[intel, Nvidia, razer, white]

Note: if you are looking for the list to be as [: intel, : Nvidia, : razer, : white], replace list.add(item.substring(item.indexOf(":") + 1).trim()); with list.add(item.substring(item.indexOf(":")).trim());.

Feel free to comment if you are looking for something else.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

An evergreen solution is :

String string = "Computer: intel, graphic card: Nvidia,";

Map<String,String> map = Pattern.compile("\\s*,\\s*")
    .splitAsStream(string.trim())
    .map(s -> s.split(":", 2))
    .collect(Collectors.toMap(a -> a[0], a -> a.length>1? a[1]: ""));
System.out.println(map.values());

Output:

[ Nvidia,  intel]
Vishwa Ratna
  • 5,567
  • 5
  • 33
  • 55
0

You can use regex for that. To extract the text between a : and the last , in the line, use something like:

(?<=\:)(.*?)(?=\,\n)

You can then perform an operation like this:

String mytext = "Computer: intel, graphic card: Nvidia,\n" + 
                  "Mouse: razer, color: white etc.";
Pattern pattern = Pattern.compile("(?<=\:)(.*?)(?=\,\n)");
Matcher matcher = pattern.matcher(mytext);
if (matcher.find())
{
    System.out.println(matcher.group(1));
}

The output will be:

 intel, graphic card: Nvidia

Inspired by this and this other threads.

Sir Beethoven
  • 348
  • 1
  • 8
0

modify your code as follows to solve the issue.

Scanner sc = new Scanner(new File(path));

    ArrayList<String> list = new ArrayList<String>();

    while (sc.hasNextLine()) {
        String str = sc.nextLine();

         String[] sp = testString.split(",");

        for(int i=0;i<sp.length;i++){
            list.add(sp[i].split(":")[1]);
        }
    }

// you will get the list as intel ,nvdia, razor etc..

Chiran K.
  • 406
  • 3
  • 16
0

I think in order to get all the keys between ':' and ',' it would be good to split each line by ','and each element of the line by ':' then get the right hand value.

Please try this code :

Scanner sc;
    try {
        sc = new Scanner(new File(path));

    ArrayList<String> list = new ArrayList<String>();
    while (sc.hasNextLine()) {
        String informations = sc.nextLine();
        String[] parts = informations.split(",");
        for( String part : parts) {
            list.add(part.substring(part.indexOf(':')+1));
        }
    }
    }
     catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }