【问题标题】:Java Letter changes arraylist to string without commas but including white spacesJava Letter 将 arraylist 更改为不带逗号但包含空格的字符串
【发布时间】:2016-06-10 05:47:43
【问题描述】:

试图从 coderbyte 完成这个挑战:“使用 Java 语言,让函数 LetterChanges(str) 获取传递的 str 参数并使用以下算法对其进行修改。将字符串中的每个字母替换为它后面的字母字母表(即 c 变为 d,z 变为 a)。然后将这个新字符串中的每个元音大写(a,e,i,o,u),最后返回这个修改后的字符串。"

我遇到的问题是替换是拉动字符之间的空格,但我需要它来保留单词之间的空格。有没有更好的解决方案?

import java.util.Arrays;
import java.util.Scanner;

public class nextLetter {
    public static String LetterChanges(String str) {
        String[] inputString = str.replaceAll("[^a-zA-Z ]", "").split("");
        String[] alph= "abcdefghijklmnopqrstuvwxyz".split("");
        String[] vowel ="aeiouy".split("");
        for(int i=0; i<inputString.length; i++){
            int index= Arrays.asList(alph).indexOf(inputString[i])+1;
            inputString[i]= alph[index];
            if(Arrays.asList(vowel).indexOf(inputString[i])>0){
                inputString[i]= inputString[i].toUpperCase();
            }
        }
        //System.out.println(Arrays.toString(inputString));
        return Arrays.toString(inputString)
                .replace(" ","")
                .replace(",", "")  //remove the commas
                .replace("[", "")  //remove the right bracket
                .replace("]", "")//remove the left bracket
                .replace(" ","")
                .trim();
    }
    public static void main(String[] args) {
     Scanner s = new Scanner(System.in);
     System.out.println("enter a sentence");
     System.out.print(LetterChanges(s.nextLine())); 
}
}

我也不介意任何关于如何改进这一点的建议!

【问题讨论】:

  • 那么,你的问题到底是什么?
  • 当我输入“测试句”时,输出是 UftUatfOUfOdf,当它仍然应该是 2 个单独的“单词”时
  • 您正在删除所有的空白。如果您想保留它,请不要删除它。无论如何,@Michael 有更好的方法。
  • 通过代码的演练更新了我的答案

标签: java arrays arraylist replace


【解决方案1】:

注意:我已将方法名称更改为更具描述性的名称。该方法假定您只使用小写字母。

public static void main(String[] args){
    System.out.println(shiftLetters("abcdz")); //bcdea
}

public static String shiftLetters(String str){
    StringBuilder shiftedWord = new StringBuilder();

    for (int i = 0; i < str.length(); i++){
        char currentChar = str.charAt(i);
        if (currentChar != ' '){
            currentChar += 1;
            if (currentChar > 'z'){
                currentChar = 'a';
            }
        }
        shiftedWord.append(currentChar);
    }

    return shiftedWord.toString();
}

这是这个程序的一般逻辑流程:创建一个累积的StringBuilder对象,最终将是方法的返回值。循环遍历字符串中的所有字符;如果该字符是一个空白字符,那么就不要理会它并将其按原样添加到StringBuilder 中。 Else,给当前字符加一。请注意chars 是integral(4.2.1) 原始类型,因此您可以将ints 添加到char 中。如果是新的char 超出正常a-z 范围的特殊情况,请将其设置回a

使用 Java 8 的 API

public static String functionalShiftLetters(String str){
    return str
        .chars()
        .map(c -> c != ' ' ? c + 1 : c)
        .map(c -> c > 'z'? 'a' : c)
        .collect(StringBuilder::new,
                   StringBuilder::appendCodePoint, StringBuilder::append)
        .toString();
}

【讨论】:

    【解决方案2】:

    这会保留所有其他字符并处理元音。

    public static String LetterChanges(String str)
    {
        str = str.toLowerCase();
        StringBuilder sb = new StringBuilder();
    
        for (int i = 0; i < str.length(); i++)
        {
            char c = str.charAt(i);
    
            if ('a' <= c && c <= 'z')
            {
                c = (c == 'z') ? 'a' : (char) (c + 1);
    
                if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
                {
                    c = Character.toUpperCase(c);
                }
            }
            sb.append(c);
        }
        return sb.toString();
    }
    

    输入:abcdefghijklmnopqrstuvwxyz 1234567890

    输出:bcdEfghIjklmnOpqrstUvwxyzA 1234567890

    【讨论】:

      【解决方案3】:

      如果有固定的字母和交换算法,您可以使用静态字典。

      public static HashMap<String,String> dictionary = new HashMap<>();
      
          static{
              dictionary.put(" ", " ");
              dictionary.put("a", "b");
              dictionary.put("b", "c");
              dictionary.put("c", "d");
              dictionary.put("d", "E");
              .
              .
              dictionary.put("z", "A");
          }
      
          public static  String shiftLetters(String str){         
              StringBuffer response = new StringBuffer();
      
              for (int i = 0; i < str.length(); i++){
                  response.append(dictionary.get(String.valueOf(str.charAt(i))));
              }
      
              return response.toString();
          }   
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-28
        • 1970-01-01
        • 2017-10-20
        • 1970-01-01
        • 1970-01-01
        • 2016-06-18
        • 2013-05-31
        • 2016-03-31
        相关资源
        最近更新 更多