我想创建一个循环,它可以在字符串中找到空格,然后对字符串进行处理

i want to create a loop which can find white spaces in a sting and then do processing on the string

所以考虑字符串为 Y = ABCD EFG AIJ 现在,Z1、Z2 和 Z3 是循环中的三行。

  1. 所以循环的工作方式应该是它首先识别白色 space 即 X1 = 5 然后下一条语句应该是子串(Y,1,X1-1);输出将是:- Z1 = ABCD

  2. second statement 应该确定第二个 white space 即 X2 = 9 第二个语句应该是 子串(Y,X1+1,X2-1);输出应该是 Z2 = EFG

等等。

一旦我们有了 Z1、Z2 和 Z3 我想将 Z1 的第一个字符与 Z2 进行比较并重新排序我的字符串中的文本。

例如

如果; A > E 然后重新排序并用 E 替换 A 如果; A < E 然后相同的顺序。

谁能帮忙。

在 java 中,字符串 class 有拆分方法,所以你可以简单地说

//arr will have multiple items - arr[0]="ABCD";arr[1]="EFG";arr[2]="AIJ"
String[] arr = Y.split(" ");

现在我想了解你的意思:-

如果;如果 A > E,则重新排序并用 E 替换 A; A < E 然后相同的顺序。 你要排序吗?

这是你想要的吗? -

  public static void main(String[] args) {

    String str = "abcd efg aij";
    System.out.println(str);
    int len = str.length();
    int[] pos = new int[len];
    for(int j=0;j<len;j++){
        if(str.charAt(j) == ' '){
            pos[j] = j;
        }else{
            pos[j] = -1;
        }
    }
    str = str.replace(" ","");
        int[] arr = new int[str.length()];
        for(int i=0; i<arr.length; i++){
            arr[i] = str.charAt(i);
        }
    Arrays.sort(arr);
    String str1="";
    for (int number : arr) {
        str1+=Character.toString ((char) number);

        }

    for(int k =0; k<str1.length(); k++){

        if(pos[k] != -1){
            System.out.print(" ");
        }

        System.out.print(str1.charAt(k));
    }



}