简体   繁体   中英

Java - cut string in a specific way

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.

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.

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.

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]

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.

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..

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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM