Java 我想在不使用拆分功能的情况下拆分字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2939691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:41:20  来源:igfitidea点击:

I want to split string without using split function?

java

提问by Sanjeev

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

我想在不使用 split 的情况下拆分字符串。任何人都可以解决我的问题我尝试过但我找不到确切的逻辑。

采纳答案by polygenelubricants

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 indexOfwith the fromIndexparameter to find all occurrences of a substring within a larger string:

下面是一个indexOffromIndex参数一起使用以查找较大字符串中所有出现的子字符串的示例:

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

字符串 API 链接

  • 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 substringat given indices out of a string and puts them into a List<String>:

此代码段substring从字符串中提取给定索引并将它们放入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
  • Effective Java 第 2 版,第 25 条:列表优先于数组
    • 如果您事先不知道有多少零件,效果会特别好

String API links

字符串 API 链接

Related questions

相关问题

回答by Matchu

Since this seems to be a task designed as coding practice, I'll only guide. No code for you, sir, though the logic and the code aren't that far separated.

由于这似乎是一项设计为编码练习的任务,因此我只会进行指导。没有代码给你,先生,虽然逻辑和代码相距不远。

You will need to loop through each character of the string, and determine whether or not the character is the delimiter (comma or semicolon, for instance). If not, add it to the last element of the array you plan to return. If it is the delimiter, create a new empty string as the array's last element to start feeding your characters into.

您需要遍历字符串的每个字符,并确定该字符是否为分隔符(例如逗号或分号)。如果没有,请将其添加到您计划返回的数组的最后一个元素。如果它是分隔符,则创建一个新的空字符串作为数组的最后一个元素,以开始将字符输入其中。

回答by Hyman

The logic is: go through the whole string starting from first character and whenever you find a space copy the last part to a new string.. not that hard?

逻辑是:从第一个字符开始遍历整个字符串,每当你找到一个空格时,将最后一部分复制到一个新字符串中......不难吗?

回答by Babiker

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

您不能不使用 split() 进行拆分。您唯一的其他选择是获取字符串字符索引并获取子字符串。

回答by Roland Illig

The way to go is to define the function you need first. In this case, it would probably be:

要走的路是先定义你需要的函数。在这种情况下,它可能是:

String[] split(String s, String separator)

The return type doesn't have to be an array. It can also be a list:

返回类型不必是数组。它也可以是一个列表:

List<String> split(String s, String separator)

The code would then be roughly as follows:

代码大致如下:

  1. start at the beginning
  2. find the next occurence of the delimiter
  3. the substring between the end of the previous delimiter and the start of the current delimiter is added to the result
  4. continue with step 2 until you have reached the end of the string
  1. 从头开始
  2. 找到下一次出现的分隔符
  3. 将前一个分隔符的结尾和当前分隔符的开头之间的子字符串添加到结果中
  4. 继续第 2 步,直到到达字符串的末尾

There are many fine points that you need to consider:

您需要考虑很多细节:

  • What happens if the string starts or ends with the delimiter?
  • What if multiple delimiters appear next to each other?
  • What should be the result of splitting the empty string? (1 empty field or 0 fields)
  • 如果字符串以分隔符开头或结尾会发生什么?
  • 如果多个分隔符相邻出现怎么办?
  • 拆分空字符串的结果应该是什么?(1 个空字段或 0 个字段)

回答by Peter Tillemans

You do now that most of the java standard libraries are open source

您现在知道大多数 Java 标准库都是开源的

In this case you can start here

在这种情况下,您可以从这里开始

回答by DemonHunter

You can do it using Java standard libraries.

您可以使用 Java 标准库来实现。

Say the delimiter is :and

说分隔符是:

String s = "Harry:Potter"
int a = s.find(delimiter);

and then add

然后添加

s.substring(start, a)

to a new String array.

到一个新的字符串数组。

Keep doing this till your start < string length

继续这样做直到你 start < string length

Should be enough I guess.

我想应该足够了。

回答by Sanjeev

This is the right answer

这是正确答案

import java.util.StringTokenizer;

public class tt {
    public static void main(String a[]){
    String s = "012ab567ab0123ab";

    String delims = "ab ";

    StringTokenizer st = new StringTokenizer(s, delims);
            System.out.println("No of Token = " + st.countTokens());

             while (st.hasMoreTokens())
             {
                 System.out.println(st.nextToken());
             }

     }

}

回答by Rakesh Sahu

Use String tokenizer to split strings in Java without split:

使用 String 标记器在 Java 中拆分字符串而无需split

import java.util.StringTokenizer;

public class tt {
    public static void main(String a[]){
        String s = "012ab567ab0123ab";
        String delims = "ab ";
        StringTokenizer st = new StringTokenizer(s, delims);
        System.out.println("No of Token = " + st.countTokens());
        while (st.hasMoreTokens()) {
            System.out.println(st.nextToken());
        }
    }
}

回答by Akhilesh Dhar Dubey

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

}