将字符串中的字母提升为java中的下一个字母

时间:2011-01-15 06:13:51

标签: java

我遇到问题,弄清楚如何让我的代码增加用户输入给出的字符串,这样当用户选择替换像z这样的字母时,它会转到a,b到c等。我必须这样做而不使用布尔值。我应该通过使用算术来从用户输入获得从z到a的促销。加上必须只是a-z的小写字母。任何帮助将不胜感激。

8 个答案:

答案 0 :(得分:18)

这段代码

String foo = "abcdefz";
String bar = "";

for (char c : foo.toCharArray()) {
   bar += Character.toString((char) (((c - 'a' + 1) % 26) + 'a'));
}

System.out.println(bar);

将输出

bcdefga

它做的是取字符,减去'a'的字符代码,从而得到0到25​​之间的值。然后我们递增1.得到答案并执行模数26,所以如果我们有'z' ,我们减去'a',从而给出25 + 1 = 26,模数26 = 0.然后我们再添加'a'并vo!

** 编辑 **

你甚至可以进一步推动这个概念并添加一个变量“移位”值:

int shiftValue = 12;

String foo = "abcdefz";
String bar = "";

for (char c : foo.toCharArray()) {
   bar += Character.toString((char) (((c - 'a' + shiftValue) % 26) + 'a'));
}

System.out.println(bar);

将输出

mnopqrl

shiftValue的值可以是任何正整数(即,移位-2与移位24相同)。试试吧。

** 更新 **

好吧,只需用等式替换你的alpha + 1。并不是说我想给你提供一切,但如果你必须坚持,这就是你需要做的事情:

** 免责声明 **:包含您的家庭作业解决方案

// define some constants
char FIRST_LETTER = 'a';    // the first letter in the alphabet
int ALPHABET_SIZE = 26;     // the number of letters in the alphabet
int SHIFT_VALUE = 1;        // number of letters to shift

Scanner kb = new Scanner(System.in);
String second = "hello world";    // target string

String alphabet = kb.next();
// TODO: need to check if alphabet has at least one char and if it's in the range of a-z
char alpha = alphabet.charAt(0);   // just keep the first char in the input
System.out.println(second.replace(alpha, (char) (((alpha - FIRST_LETTER + SHIFT_VALUE) %  ALPHABET_SIZE ) + FIRST_LETTER)));

将输出

l
hemmo wormd

** 编辑2 **

如果你有一个基于索引的字母(如果你需要包含额外的字符等),这是另一个解决方案。没有评论也没有优化,但代码有效且应该是自我解释的......仅供参考:

int shiftValue = 1;
char[] alphabet = new char[] {
   'a','b','c','d','e','f','g','h','i',
   'j','k','l','m','n','o','p','q','r',
   's','t','u','v','w','x','y','z','!',' '
};
boolean[] replace = new boolean[alphabet.length];

Scanner kb = new Scanner(System.in);
String text = "hello world !";

System.out.print("$ ");
String input = kb.nextLine().toLowerCase();

Arrays.fill(replace, false);
for (char c : input.toCharArray()) {
   int index = -1;
   for (int i=0; i<alphabet.length; i++) {
      if (alphabet[i] == c) {
         index = i;
         break;
      }
   }
   if (index >= 0) {
      replace[index] = true;
   }
}

for (int i=alphabet.length - 1; i>0; i--) {
   if (replace[i]) {
      text = text.replace(alphabet[i], alphabet[(i+shiftValue) % alphabet.length]);
   }
}
System.out.println(text);

当然,此代码将替换text字符串中从 stdin 读取的每个char。输出的一个例子是:

$ ! e wo
hfllpaxprlda 

答案 1 :(得分:2)

String s = "q";
char c = s.charAt(0);
c++;
//here you can handle cases like z->a
if (c=='z') c = 'a';

char[] chars = new char[1];
chars[0] = c;
String s1 = new String(chars);

答案 2 :(得分:2)

又一个选项,将==测试隐藏在交换机中:

public static void main(String[] args)
{

    char[] chars = {'a','k','f','z'};
    for (char letter : chars) {
        char next = letter;
        switch (next) {
        case 122: // or 'z', either way
            next ='a';
            break;
        default:
            next += 1;
        }
        System.out.println(letter + " is followed by " + next + " ");
    }

}

答案 3 :(得分:1)

Map<Character, Character> s = new HashMap<Character, Character>();
s.put('a', 'b');
...
s.put('z', 'a');


String s = "q";
char c = s.charAt(0);

c = s.get(c);

char[] chars = new char[1];
chars[0] = c;
String s1 = new String(chars)

答案 4 :(得分:1)

我有以下答案。它处理字符串之间的空白区域。当你有一个'z',这是字母表的结尾时,你不能去下一个字符,所以我把它带到了开头,这是一个。

import java.util.Scanner;

public class NextChar {

    public static char nextCharacterInAlphabet(char character)
    {
        char nextChar;           
        int ascii = (int) character;

        if (ascii ==32)  //ascii code for a space is 32
            /*space stays space that separates the different 
            strings seperated by the spaces */
            nextChar = (char) ascii;   
        else if (ascii == 122)
            /*if the character is a z, then there is no 
            next character so i let i go back to the first character in alphabet*/
        nextChar = (char) (ascii -25); //alphabet has 26 chars, z=26 -25 is first char
              else //if the char is not a space or z then it goes to the next char
                nextChar = (char) (ascii +1);
        return nextChar; 
    }

    public static void main(String[] args) {

        Scanner input = new Scanner( System.in );
        StringBuffer sb = new StringBuffer(); //to store the characters

        for (char c : input.nextLine().toCharArray() ) //loops through the char array
        {
            sb.append(nextCharacterInAlphabet(c)); //appends the chars to the stringbuffer passed to it by the method 
        }
        System.out.println(sb.toString()) ; 
    }
}

答案 5 :(得分:0)

也许对某人有用:

import java.util.Scanner;
public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String ss = new String();
        System.out.print("Enter String:");

    for(char c : input.nextLine().toCharArray() ){
        // Checking given string must cantain only [a-zA-Z\s] values (by  ASCII Table);
        // (condition) char value must be alphabeticl value by ASCII Table
        if ( ( (int)c >= 65 ) && ((int)c <= 90) || ((int)c >= 97) && ((int)c <= 122) ) {
            switch ((int)c ) {
                case 90:
                    ss += "A";
                    break;
                case 122:
                    ss += "a";
                    break;
                default:
                    ss += (char)(c+1);
            }// switch() increment every char by one

        }else if( (int)c == 32 ){
            ss += " ";
        }else{
            ss +=(char)(c);
        }// if(char value must alphabetical ASCII condition);

    } // --For Loop 

    System.out.println("\nnew String: "+ss);

} // main();

答案 6 :(得分:0)

根据数组长度滚动每个字符,当字符值大于'z'时将值更改为'a'

public static String stringRoll(String str, int[] arr) {
       char[] charArr = str.toCharArray();
       int valueOfZ = 'z';
      for(int i = 0; i < arr.length; i++){
          for(int j = 0; j < arr[i]; j++){
                int value = charArr[j] + 1;
               if(value > valueOfZ) {
                    charArr[j] = 'a';
                }else{
                  charArr[j] = (char) value;
           }
       }
   }
   return new String(charArr);
}

答案 7 :(得分:0)

公共类 ReplaceWithNextChar {

public static void main(String[] args)
{
  Scanner sc1=new Scanner(System.in);
  System.out.println("Enter the String");
  String s=sc1.nextLine();
  char[] ch=s.toCharArray();
  int val=0;
  String s1="";
  for(int i=0;i<ch.length;i++)
  {
      val=ch[i]+1;
      char c=(char)val;
      s1=s1+c;
  }
  System.out.println(s1);
}

}