![](/img/trans.png)
[英]Replace every letter of string with next letter in alphabet but preserve spaces and punctuation?
[英]What is the best way to replace a letter with the letter following it in the alphabet in Java?
我是一個編程新手,我正在做一個 coderbyte 練習,上面寫着“用字母表中的字母替換字符串中的每個字母(即 c 變為 d,z 變為 a)”
我正在考慮以下方法:
最簡單的方法是什么?
編輯這是我到目前為止的代碼,但它不起作用。
import java.util.*;
import java.io.*;
class Main {
public static String LetterChanges(String str) {
// code goes here
String alphabet = "abcdefghijklmnopqrstuvwxyz";
String newWord = "";
for (int i = 0; i < str.length(); i++){
for (int j = 0; j < alphabet.length(); i++){
if (str[i] == alphabet[i]){
if (alphabet[i+1].isVowel()){
newWord = newWord + toUpperCase(alphabet[i+1]);
}
else{
newWord = newWord + alphabet[i+1];
}
}
}
}
return str;
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LetterChanges(s.nextLine()));
}
}
我不能要求作為字符串一部分的 Char 的索引 position 嗎? 在 C 我可以做到這一點。 除此之外不知道為什么它不起作用。
我肯定會用方法1 go。
我相信您正在尋找的是String
上的indexOf
方法。 首先,我將創建一個給定字符的方法,它會在字母表中找到下一個字母並返回它。 這可以通過在字母字符串中找到字母然后在 index+1 處獲取字母來完成。 正如您還指出的那樣,您需要注意邊緣情況以將“z”轉換為“a”,這可以通過使用 if 語句或在字母字符串末尾添加一個額外的字母“a”來完成。
現在剩下要做的就是創建一個遍歷消息中所有字符的循環,並在該字符上調用先前創建的方法,並使用 output 構造一個新字符串。
希望這可以幫助您找到解決方案。
假設在給定的String
中只有小寫英文字母,最高效的方法是向每個字符添加+1
,並使用if
語句檢查初始字符是否為z
或使用模運算符%
作為@sp00m已在評論中指出。
在字母字符串(列表中的選項 1 )中執行搜索是多余的,以及從給定字符串(選項 3 )中提取數組char[]
。
檢查邊緣情況:
public static String shiftLetters(String str) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char next = str.charAt(i);
if (next == 'z') result.append('a'); // checking the edge case
else result.append((char) (next + 1));
}
return result.toString();
}
應用模運算符:
public static String shiftLetters(String str) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char next = (char) ((str.charAt(i) - 'a' + 1) % 26 + 'a');
result.append(next);
}
return result.toString();
}
main()
public static void main(String[] args) {
System.out.println(shiftLetters("abc"));
System.out.println(shiftLetters("wxyz"));
}
Output:
bcd // "abc"
xyza // "wxyz"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.