Promoting letters in a string to the next letter i

2020-02-26 12:12发布

I'm having issues figuring out how to get my code to increment the string that is given by user input so that when a user chooses to replace a letter like z it would go to a, b to c etc. The catch is I have to do this without using boolean. I am supposed to get this by using arithmetics to get the promotion from z to a from the users input. Plus must be only lower case letters from a-z. Any help would be appreciated thanks.

标签: java
7条回答
Fickle 薄情
2楼-- · 2020-02-26 12:34
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);
查看更多
▲ chillily
3楼-- · 2020-02-26 12:35

This piece of code

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

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

System.out.println(bar);

will output

bcdefga

What it does is take the character, substract the character code for 'a', thus given a value from 0 to 25. Then we increment 1. Take that answer and perform a modulus 26, so if we had 'z', we substract 'a' thus giving 25 + 1 = 26, modulus 26 = 0. We then add 'a' again and voilà!

** EDIT **

You can even push the concept a little further and add a variable "shifting" value :

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

Will output

mnopqrl

The value of shiftValue may be any positive integer (i.e. shifting -2 is the same as shifting 24). Try it.

** UPDATE **

Well, just replace your alpha+1 with the equation. Not that I want to feed you everything, however if you must insist, here is what you need to do :

** DISCLAIMER ** : contains your homework solution

// 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)));

Will output

l
hemmo wormd

** EDIT 2 **

If you have an index-based alphabet (in case you need to include extra chars, etc.) here's another solution. There is no comment and no optimization, but the code works and should be self explanatory... FYI only :

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

Naturally, this code will replace every char read from stdin in the text string. An example of output would be :

$ ! e wo
hfllpaxprlda 
查看更多
放荡不羁爱自由
4楼-- · 2020-02-26 12:42
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)

;

查看更多
Explosion°爆炸
5楼-- · 2020-02-26 12:47

yet another option, hiding the == test in a switch:

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 + " ");
    }

}
查看更多
贼婆χ
6楼-- · 2020-02-26 12:48

May be it will useful for someone:

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();
查看更多
家丑人穷心不美
7楼-- · 2020-02-26 12:49

I have the following answer. It takes care of the white spaces in between strings of characters. also when you have a 'z', which is the end of the alphabet, you can't go to the next character, so i made it go to the beginning, which is a.

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()) ; 
    }
}
查看更多
登录 后发表回答