[英]How to rotate a single character based on a specific range of ascii characters in Java?
I am trying to come up with a function that accepts a character and a number. 我正在尝试提出一个接受字符和数字的函数。 The number is the number of times the character should be "rotated".
该数字是字符应“旋转”的次数。 The accepted ASCII codes are 32 to 126.
可接受的ASCII码是32到126。
Example of rotate = If a character "A" was rotated twice, it would end up as the character "C". 旋转示例=如果将字符“ A”旋转两次,则最终将其作为字符“ C”。 If "A" was rotated three times, it would end up as the letter "D".
如果将“ A”旋转三遍,则最终以字母“ D”结尾。 If you look at the ASCII table:
如果您查看ASCII表:
http://www.jimprice.com/ascii-0-127.gif http://www.jimprice.com/ascii-0-127.gif
Given my limit of the ASCII value being 32 to 126... ascii value 065 rotated would be ascii value 067. ascii value 124 rotated 5 times would be ascii value 34. 给定我的ASCII值限制为32到126 ...旋转的ascii值065将是ascii值067。旋转5次的ascii值124将是ascii值34。
For example: 例如:
What is the best way to accomplish this in java (can it support negative numbers for the distance to rotate instead of just positive if you want to rotate the other way around)? 在Java中完成此操作的最佳方法是什么(如果您想反方向旋转,它可以支持负数来旋转距离而不是仅支持正数)吗?
Try something like: 尝试类似:
static char rotate(char c, int distance) {
assert 32 <= c && c < 127;
if (distance < 0) distance = distance % (127 - 32) + 127 - 32;
return (char) ((c + distance - 32) % (127 - 32) + 32);
}
Edit: Added the if (distance
... line to support negative distances. 编辑:添加了
if (distance
...行以支持负距离。
Do like this 像这样
public static char numToChar(int num,int rotate){
int result = num+rotate;
if(result>126){
result =31+(result-126);
}
return (char)result;
}
System.out.println(numToChar(33,2));
System.out.println(numToChar(125,3));
Output 产量
#
!
You could use this approach 您可以使用这种方法
public static char rotateChar(char in, int shift) {
/* cast char to int */
int v = (int) in;
/* to cover wrap-around */
v += (shift % 95);
/* 32 - 126 = -95 */
return (char) ((v > 126) ? v - 95 : v);
}
public static void main(String[] args) {
System.out.printf("! + 2 = %s\n",
String.valueOf(rotateChar('!', 2)));
System.out.printf("} + 3 = %s\n",
String.valueOf(rotateChar('}', 3)));
System.out.printf("b - 1 = %s\n",
String.valueOf(rotateChar('b', -1)));
}
! + 2 = #
} + 3 = !
b - 1 = a
Try This. 尝试这个。
public static void main(String[] args) {
String ascii;
String rotate;
Scanner in = new Scanner(System.in);
System.out.println("Enter ASCII Character");
ascii = in.nextLine();
System.out.println("Enter Rotate value");
rotate = in.nextLine();
int output=(Integer.parseInt(ascii)+Integer.parseInt(rotate))% 126;
if(output<32) output=output+32;
System.out.println("output="+output);
System.out.println(Character.toString ((char) output));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.