2

Здравствуйте, возможно ли выполнить подобное? Как перевести символьный массив в строку я знаю, а как наоборот?

char ich[] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' };
String str;
str = in.next();
len = str.length();
System.out.println("Length your message");
System.out.println(len);
for (i = 0; i < len; i++)
    ich[i] = str[i];
1

1 ответ 1

2

Методы класса String

  1. toCharArray()

     /**
     * Converts this string to a new character array.
     *
     * @return  a newly allocated character array whose length is the length
     *          of this string and whose contents are initialized to contain
     *          the character sequence represented by this string.
     */
    public char[] toCharArray() {
        // Cannot use Arrays.copyOf because of class initialization order issues
        char result[] = new char[value.length];
        System.arraycopy(value, 0, result, 0, value.length);
        return result;
    }
    

    Пример: "SomeText".toCharArray(); - строка в символьный массив.

  2. valueOf(char data[])

     /**
     * Returns the string representation of the {@code char} array
     * argument. The contents of the character array are copied; subsequent
     * modification of the character array does not affect the returned
     * string.
     *
     * @param   data     the character array.
     * @return  a {@code String} that contains the characters of the
     *          character array.
     */
    public static String valueOf(char data[]) {
        return new String(data);
    }
    

    Пример: String.valueOf(charArr); - символьный массив в строку.

2
  • Можно ещё new String(charArr) 4 дек 2017 в 18:32
  • String str; System.out.println("Message"); str = in.next(); len = str.length(); for (i = 0; i < len; i++) ich[i] = str.toCharArray(); Выдает ошибку, типа запрашивается char, а получает char[]
    – Marhell
    4 дек 2017 в 18:54

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.