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

时间:2018-06-01 12:30:14

标签: java

我有一个字符串s1,我想在指定的位置添加另一个字符串String s = "17.4755,2.0585,23.6489,12.0045"; String s1=",,,,"

s1

现在我想在第{n}个","字符后添加字符串{{1}}。

我刚开始学习Java。

3 个答案:

答案 0 :(得分:1)

您可以使用以下方法:

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

答案 1 :(得分:0)

直接与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

答案 2 :(得分:0)

我认为这就是你想要的

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


}

}
  

输出:

1. Enter Nth Occurrence
5
String s have only 3 symbol ","


2. Enter Nth Occurrence
2
17.4755,2.0585,,,,,23.6489,12.0045