문자를 Java의 ASCII 숫자 값으로 변환
있다String name = "admin";
나서 나는 한다String charValue = name.substring(0,1); //charValue="a"
하고 charValue
ASCII ( 97 ) 。바에 는어 ?? ?? ???
아주 간단합니다.해 주세요.char
로 int
.
char character = 'a';
int ascii = (int) character;
이 경우 String에서 특정 문자를 먼저 가져온 후 캐스팅해야 합니다.
char character = name.charAt(0); // This gives the character 'a'
int ascii = (int) character; // ascii is now 97.
캐스트는 명시적으로 필요하지 않지만 가독성이 향상됩니다.
int ascii = character; // Even this will do the trick.
단지 다른 접근법
String s = "admin";
byte[] bytes = s.getBytes("US-ASCII");
bytes[0]
【ASCII】【ASCII】【ASCII】【ASCII】【ASCII】【】【】【】전체 배열의 다른 문자도 마찬가지입니다.
이것 대신:
String char = name.substring(0,1); //char="a"
하다를 돼요.charAt()
★★★★★★ 。
char c = name.charAt(0); // c='a'
int ascii = (int)c;
Java 문자는 ASCII 문자가 아니기 때문에 이 방법을 나타내는 몇 가지 답변은 모두 올바르지 않습니다.Java는 Unicode 문자의 멀티바이트 인코딩을 사용합니다.Unicode 문자 세트는 ASCII의 슈퍼 세트입니다.따라서 Java 문자열에는 ASCII에 속하지 않는 문자가 포함될 수 있습니다.이러한 문자에는 ASCII 숫자 값이 없기 때문에 Java 문자의 ASCII 숫자 값을 얻는 방법을 묻는 것은 대답할 수 없습니다.
근데 왜 이러는 거야?그 가치를 어떻게 할 건가요?
Java String을 ASCII 문자열로 변환할 수 있도록 수치 값을 원하는 경우 실제 질문은 "Java String을 ASCII로 인코딩하려면 어떻게 해야 합니까?"입니다.그러기 위해서는 object를 사용합니다.
문자열 전체를 연결된 ASCII 값으로 변환하는 경우 다음을 사용할 수 있습니다.
String str = "abc"; // or anything else
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray())
sb.append((int)c);
BigInteger mInt = new BigInteger(sb.toString());
System.out.println(mInt);
979899를 출력으로 얻을 수 있습니다.
이건 칭찬할 만한 일이야.
다른 사람들이 편할 수 있도록 그냥 여기에 복사해 놨어요.
char를 int로 변환합니다.
String name = "admin";
int ascii = name.toCharArray()[0];
기타:
int ascii = name.charAt(0);
int에 char를 던져주세요.
char character = 'a';
int number = (int) character;
「」의 값number
97엔이 됩니다.
이미 몇 가지 형태로 답변이 끝난 것을 알고 있습니다만, 여기 모든 문자를 살펴볼 수 있는 코드의 일부가 있습니다.
여기 코드가 있습니다. 수업부터 시작합니다.
public class CheckChValue { // Class name
public static void main(String[] args) { // class main
String name = "admin"; // String to check it's value
int nameLenght = name.length(); // length of the string used for the loop
for(int i = 0; i < nameLenght ; i++){ // while counting characters if less than the length add one
char character = name.charAt(i); // start on the first character
int ascii = (int) character; //convert the first character
System.out.println(character+" = "+ ascii); // print the character and it's value in ascii
}
}
}
public class Ascii {
public static void main(String [] args){
String a=args[0];
char [] z=a.toCharArray();
for(int i=0;i<z.length;i++){
System.out.println((int)z[i]);
}
}
}
간단하게 원하는 캐릭터를 구해서 int로 변환할 수 있습니다.
String name = "admin";
int ascii = name.charAt(0);
이를 위한 간단한 방법은 다음과 같습니다.
int character = 'a';
"캐릭터"를 인쇄하면 97이 됩니다.
String str = "abc"; // or anything else
// Stores strings of integer representations in sequence
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray())
sb.append((int)c);
// store ascii integer string array in large integer
BigInteger mInt = new BigInteger(sb.toString());
System.out.println(mInt);
String name = "admin";
char[] ch = name.toString().toCharArray(); //it will read and store each character of String and store into char[].
for(int i=0; i<ch.length; i++)
{
System.out.println(ch[i]+
"-->"+
(int)ch[i]); //this will print both character and its value
}
@Raedwald가 지적했듯이, Java의 Unicode가 ASCII 값을 얻기 위해 모든 문자를 지원하는 것은 아닙니다.올바른 방법(Java 1.7+)은 다음과 같습니다.
byte[] asciiBytes = "MyAscii".getBytes(StandardCharsets.US_ASCII);
String asciiString = new String(asciiBytes);
//asciiString = Arrays.toString(asciiBytes)
또는 Java 1.8에서 시작하는 String 또는 String에 Stream API를 사용할 수 있습니다.
public class ASCIIConversion {
public static void main(String[] args) {
String text = "adskjfhqewrilfgherqifvehwqfjklsdbnf";
text.chars()
.forEach(System.out::println);
}
}
Java 9 = > String.chars() 사용
String input = "stackoverflow";
System.out.println(input.chars().boxed().collect(Collectors.toList()));
출력 - [115, 116, 97, 99, 107, 111, 118, 101, 114, 102, 108, 111, 119]
추가 int 변수를 사용하지 않는 한 줄 솔루션:
String name = "admin";
System.out.println((int)name.charAt(0));
이 코드로 ASCII 번호를 확인할 수 있습니다.
String name = "admin";
char a1 = a.charAt(0);
int a2 = a1;
System.out.println("The number is : "+a2); // the value is 97
제가 틀렸다면 사과드립니다.
문자열 내의 모든 문자의 ASCII 값을 원하는 경우.다음을 사용할 수 있습니다.
String a ="asdasd";
int count =0;
for(int i : a.toCharArray())
count+=i;
String 내의 단일 문자의 ASCII 를 사용하는 경우는, 다음과 같이 할 수 있습니다.
(int)a.charAt(index);
저도 같은 방법으로 시도했지만 charAt를 사용하여 인덱스에 액세스하려면 [128] 크기의 정수 배열을 만들어야 합니다.
String name = "admin";
int ascii = name.charAt(0);
int[] letters = new int[128]; //this will allocate space with 128byte size.
letters[ascii]++; //increments the value of 97 to 1;
System.out.println("Output:" + ascii); //Outputs 97
System.out.println("Output:" + letters[ascii]); //Outputs 1 if you debug you'll see 97th index value will be 1.
완전한 String의 ASCII 값을 표시하려면 이 작업을 수행해야 합니다.
String name = "admin";
char[] val = name.toCharArray();
for(char b: val) {
int c = b;
System.out.println("Ascii value of " + b + " is: " + c);
}
이 경우 출력은 다음과 같습니다.a의 ASCII 값: 97 ASCII 값 d는 100 ASCII 값: 109 ASCII 값 i는 105 ASCII 값 n은 110입니다.
간단한 방법은 다음과 같습니다.
문자열 전체를 ASCII로 변환하는 경우:
public class ConvertToAscii{
public static void main(String args[]){
String abc = "admin";
int []arr = new int[abc.length()];
System.out.println("THe asscii value of each character is: ");
for(int i=0;i<arr.length;i++){
arr[i] = abc.charAt(i); // assign the integer value of character i.e ascii
System.out.print(" "+arr[i]);
}
}
}
출력은 다음과 같습니다.
THe asscii value of each character is: 97 100 109 105 110
Here,
abc.charAt(i)
gives the single character of String array: When we assign each character to integer type then, the compiler do type conversion as,
arr[i] = (int) character // Here, every individual character is coverted in ascii value
단, 단일 문자의 경우:
String name = admin; asciiValue = (int) name.charAt(0);// for character 'a' System.out.println(asciiValue);
이를 위해 String classe의
input.codePointAt(index);
java 8을 사용하여 문자열 전체를 대응하는 ASCII 코드로 변환하는 방법에 대해 하나 더 제안하고 싶습니다.예를 들어 "abcde"에서 "979899100101"로 하겠습니다.
String input = "abcde";
System.out.println(
input.codePoints()
.mapToObj((t) -> "" + t)
.collect(joining()));
언급URL : https://stackoverflow.com/questions/16458564/convert-character-to-ascii-numeric-value-in-java
'programing' 카테고리의 다른 글
확장 루프의 null 검사 (0) | 2022.06.27 |
---|---|
정확히 어떻게 이중 문자열 트릭이 작동할까요? (0) | 2022.06.27 |
Java: 경로와 파일 (0) | 2022.06.27 |
Firestore가 'onSnapshot() requires between 인수'를 슬로우합니다. (0) | 2022.06.27 |
Vuex에서 다른 액션 내에서 액션을 호출하는 것은 잘못된 관행입니까? (0) | 2022.06.27 |