I want to split string without using split functio

2020-04-16 17:33发布

I want to split string without using split . can anybody solve my problem I am tried but I cannot find the exact logic.

标签: java
15条回答
爷、活的狠高调
2楼-- · 2020-04-16 18:33

You cant split with out using split(). Your only other option is to get the strings char indexes and and get sub strings.

查看更多
对你真心纯属浪费
3楼-- · 2020-04-16 18:37

I'm going to assume that this is homework, so I will only give snippets as hints:

Finding indices of all occurrences of a given substring

Here's an example of using indexOf with the fromIndex parameter to find all occurrences of a substring within a larger string:

String text = "012ab567ab0123ab";

// finding all occurrences forward: Method #1
for (int i = text.indexOf("ab"); i != -1; i = text.indexOf("ab", i+1)) {
    System.out.println(i);
} // prints "3", "8", "14"

// finding all occurrences forward: Method #2
for (int i = -1; (i = text.indexOf("ab", i+1)) != -1; ) {
    System.out.println(i);
} // prints "3", "8", "14"

String API links

  • int indexOf(String, int fromIndex)
    • Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. If no such occurrence exists, -1 is returned.

Related questions


Extracting substrings at given indices out of a string

This snippet extracts substring at given indices out of a string and puts them into a List<String>:

String text = "0123456789abcdefghij";

List<String> parts = new ArrayList<String>();
parts.add(text.substring(0, 5));
parts.add(text.substring(3, 7));
parts.add(text.substring(9, 13));
parts.add(text.substring(18, 20));

System.out.println(parts); // prints "[01234, 3456, 9abc, ij]"

String[] partsArray = parts.toArray(new String[0]);

Some key ideas:

  • Effective Java 2nd Edition, Item 25: Prefer lists to arrays
    • Works especially nicely if you don't know how many parts there'll be in advance

String API links

Related questions

查看更多
爷、活的狠高调
4楼-- · 2020-04-16 18:37
public class MySplit {

public static String[] mySplit(String text,String delemeter){
    java.util.List<String> parts = new java.util.ArrayList<String>();
    text+=delemeter;        

    for (int i = text.indexOf(delemeter), j=0; i != -1;) {
        parts.add(text.substring(j,i));
        j=i+delemeter.length();
        i = text.indexOf(delemeter,j);
    }


    return parts.toArray(new String[0]);
}

public static void main(String[] args) {
    String str="012ab567ab0123ab";
    String delemeter="ab";
    String result[]=mySplit(str,delemeter);
    for(String s:result)
        System.out.println(s);
}

}
查看更多
登录 后发表回答