有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在字符串第n次出现后追加字符串

我有一个字符串s,我想在指定位置附加另一个字符串s1

String s = "17.4755,2.0585,23.6489,12.0045";
String s1=",,,,"

现在我想在","字符的第n次出现之后添加字符串s1

我刚刚开始学习Java


共 (3) 个答案

  1. # 1 楼答案

    我想这就是你想要的

    import java.util.Scanner;
    
    public class Test {
    
    public static void main(String[] args) {
    
        Scanner scanner = new Scanner(System.in);
    
        String s = "17.4755,2.0585,23.6489,12.0045";
    
        String s1=",,,,";
    
        System.out.println("Enter Nth Occurrence");
        try {
            int n = scanner.nextInt();
            long totalOccurrence = 0;
    
            if (n != 0) {
    
                totalOccurrence = s.chars().filter(num -> num == ',').count();
    
                if (totalOccurrence < n) {
    
                    System.out.println("String s have only " + totalOccurrence + " symbol \",\"");
    
                } else {
    
                    int count = 0;
    
                    for (int i = 0; i < s.length(); i++) {
    
                        if (s.charAt(i) == ',') {
    
                            count++;
    
                            if (count == n) {
    
                                String resultString = s.substring(0, i) + s1 + s.substring(i, s.length());
    
                                System.out.println(resultString);
    
                            }
    
                        }
    
                    }
    
                }
    
            }
    
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Wrong input");
        }
    
    
    }
    
    }
    

    Output :

    1. Enter Nth Occurrence
    5
    String s have only 3 symbol ","
    
    
    2. Enter Nth Occurrence
    2
    17.4755,2.0585,,,,,23.6489,12.0045
    
  2. # 2 楼答案

    直接使用String是不值得费心的

    一个简单的方法是将String转换为List并对其进行操作

    public void test() {
        String s = "17.4755,2.0585,23.6489,12.0045";
        // Split s into parts.
        String[] parts = s.split(",");
        // Convert it to a list so we can insert.
        List<String> list = new ArrayList<>(Arrays.asList(parts));
        // Inset 3 blank fields at position 2.
        for (int i = 0; i < 3; i++) {
            list.add(2,"");
        }
        // Create my new string.
        String changed = list.stream().collect(Collectors.joining(","));
        System.out.println(changed);
    }
    

    印刷品:

    17.4755,2.0585,,,,23.6489,12.0045

  3. # 3 楼答案

    您可以使用以下方法:

    public String insert(int n, String original, String other) {
        int index = original.indexOf(',');
        while( n > 0 && index != -1) {
            index = original.indexOf(',', index + 1);
        }
        if(index == -1) {
            return original;
        } else {
            return original.substring(0, index) + other + original.substring(index);
        }
    }