Java分裂字符串及应用方法

时间:2017-03-21 21:30:06

标签: java arrays methods split

我正在处理java中的代码,该代码会将单词内的随机字母与该单词中的另一个随机字母交换。

我需要将此代码应用于整个字符串。我遇到的问题是我的代码无法识别空格,因此每个字符串运行一次方法而不是每个字一次。如何拆分输入字符串并将方法单独应用于每个单词。这是我到目前为止所拥有的。

import java.util.Scanner;
import java.util.Random;

public class Main {
    public static void main(String[] args {
        Scanner in=new Scanner(System.in);
        System.out.println("Please enter a sentance to scramble: ");
        String word = in.nextLine();
        System.out.print(scramble(word));
    }
    public static String scramble (String word) {
        int wordlength = word.length();
        Random r = new Random();
        if (wordlength > 3) {
            int x = (r.nextInt(word.length()-2) + 1);
            int y;
            do {
                y = (r.nextInt(word.length()-2) + 1); 
            } while (x == y);
            char [] arr = word.toCharArray();
            arr[x] = arr[y];
            arr[y] = word.charAt(x);
            return word.valueOf(arr);
        }
        else {
            return word;
        }
    }
}

2 个答案:

答案 0 :(得分:0)

在String.split()中被摧毁;你可以定义一个regrex例如" "然后返回在输入上拆分的所有子串的String []返回数组

请参阅String split

示例

String in = "hello world";
String[] splitIn = in.split(" ");

您可以测试其他内容,例如"," "" &#34 ;;" ":"等等

答案 1 :(得分:0)

检查内联评论:

import java.util.Scanner;
import java.util.Random;

public class Main {
  public static void main(String[] args)
       {
          Scanner in=new Scanner(System.in);
          System.out.println("Please enter a sentance to scramble: ");
          String word = in.nextLine();


          //Split your input phrase
          String[] wordsArray = word.split(" ");
          //For each word in the phrase call your scramble function
          // and print the output plus a space
          for (String s : wordsArray){
              System.out.print(scramble(s) + " ");
          }

       }
  public static String scramble (String word) {
    int wordlength = word.length();
    Random r = new Random();
  if (wordlength > 3) {
    int x = (r.nextInt(word.length()-2) + 1);
   int y;
   do {
    y = (r.nextInt(word.length()-2) + 1); 
   } while (x == y);
   char [] arr = word.toCharArray();
   arr[x] = arr[y];
   arr[y] = word.charAt(x);
   return word.valueOf(arr);
  }
  else {
    return word;
  }
  }
}