简体   繁体   中英

Java Splitting Strings and Applying A Method

I'm working on a code in java that will swap a random letter inside of a word with another random letter within that word.

I need to apply this code to an entire string. The issue I'm having is my code can't identify white space and therefore runs the method for once per string instead of once per word. How can I split the input string and apply the method to each word individually. Here's what I have so far.

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

As destriped in teh String.split(); you can define a regrex for instance " " and then a return array of String[] for all substrings split on the input is returned

see String split

example

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

The same way you can test for other things such as "," "." ";" ":" etc

Check the inline comments:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM