2016-04-01 18 views
0

文字列をユニコードに変換し、ユニコード値に2を加えて新しい文字列を作成するアプリケーションを作成する必要があります。文字列のエンコードとデコード

入力された場合、基本的に:パスワードはRhYxtzで、出力は次のようになります。区TjAzvb rcuuyqtf

次のコードは、私がこれまで持っているものです。

public static void main(String[] args){ 

    System.out.print ("Enter text: "); 
    Scanner scan = new Scanner(System.in); 
    String text = scan.nextLine(); 

    int length = text.length(); 

    for(int i = 0; i < length; i ++){ 
     char currentChar = text.charAt(i); 
     int currentChar2 = currentChar+2; 
     String s = String.format ("\\u%04x", currentChar2); 
     System.out.println ("Encoded message: " + s); 
    } 

} 

問題があることです私はユニコードを文字列に戻す方法と、入力と同じ形式を維持する方法を知らない。誰か助けてくれますか?ありがとう。

+1

文字列は、Unicodeに既にあります。特に、すべての文字がASCII範囲にある場合は、変換を行う必要はありません。 – RealSkeptic

+0

文字列をエンコードしてエンコードしますか?文字列をエンコードしてデコードします。 https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#String(byte[],%20java.nio.charset.Charset) – StackFlowed

答えて

0

は、これを試してください

public static String encryped(String s) { 
    int[] cps = s.codePoints() 
      .mapToInt((cp) -> cp + 2) 
      .toArray(); 
    return new String(cps, 0, cps.length); 
} 

またはそれ以前のバージョンでcodePointAtとループで:

import java.util.Scanner; 
public class Example { 
    public static void main(String[] args) { 
      System.out.print ("Enter text: "); 
      Scanner scan = new Scanner(System.in); 
      String text = scan.nextLine(); 
      int length = text.length(); 
      String s = ""; 

    for(int i = 0; i < length; i ++){ 
     char currentChar = text.charAt(i); 
     if (currentChar == ' '){ 
      s += currentChar; 
     } else { 
      s += (char) (currentChar + 2); 
     } 
    } 
      System.out.println ("Encoded message: " + s); 
    } 
} 
+0

回答を追加する:あなたはそうしたように、整数を使ってUnicode文字を操作できますが、データ型はintではなくchar型になります。また、charをStringにキャストすることもできます。 ;-) – rafaelbattesti

+1

出力はrcuuyqtf "ku" Tj [zv | rcuuyqtf ku TjAzvbの代わりに。空白を残し、yとzをaとbに変換する方法はありますか? – bt203

+0

@ bt203確かに可能ですが、これは2を追加していないので混乱してしまいます。空白を保持するには、if文と 'Character.isWhitespace()'を使います。 yとzに「循環オーバーフロー」を持たせるには、別のif文を使用します。 –

0

UnicodeコードポイントとしてのJava 8で収集することができます。

Javaのchar(2バイト)はUTF-16であり、そのint値は必ずUnicodeシンボルの別名コードポイントではありません。

0

これは、米国のASCII文字のために働く必要があります。Javaで

StringBuilder buf = new StringBuilder(length); 

for(int i = 0; i < length; i ++){ 
    char currentChar = text.charAt(i); 
    if (currentChar < 128 && Character.isLetter(currentChar)) { 
     if (currentChar == 'y' || currentChar == 'z' 
       || currentChar == 'Y' || currentChar == 'Z') { 
      buf.append((char) (currentChar + 2 - 26)); 
     } else { 
      buf.append((char) (currentChar + 2)); 
     } 
    } else { 
     buf.append(currentChar); 
    } 
} 
System.out.println(buf.toString()); 
+0

これは機能します。ありがとう! – bt203

+0

もちろん、2と26という名前の定数を宣言する必要があります。 'static final int alphabetLength =(' z ' - ' a ')+ 1;のようなものです。答えを受け入れ/訂正/有用なものとしてマークしてください。 :-) –

関連する問題