【问题标题】:how to convert a String into a character array without .toCharArray instance method如何在没有 .toCharArray 实例方法的情况下将字符串转换为字符数组
【发布时间】:2015-04-23 03:00:41
【问题描述】:
// I have to prompt the user to input the String and store into Char [] array
// I know that we can use .toCharArray instance method to store the string
// into Character array.

// But I do not have to use that method, so I reference the string input to
// char array but I got an compiler error saying cannot convert string to char

// This is I have done So far
import java.util.Scanner;

/** 这个程序提示用户输入一个字符串,然后 输出整个字符串大写字母。 */

public class StringUppercase
{
    public static void main(String [] args)
    {
        String input;
        Scanner keyboard = new Scanner(System.in);

        System.out.println("Please enter a String " );
        input = keyboard.nextLine();

        char[] name;

    }
} 

【问题讨论】:

  • 不使用这种方法很愚蠢。我想你可以遍历字符串并为每个字符调用charAt(i)
  • @Thilo 这很傻,但这是一个实验室任务,所以必须按照它来。
  • 稍微不那么傻(但相当困难,特别是如果您需要支持非ASCII)将尝试完全跳过String并直接从System.in读取字符。 stackoverflow.com/questions/1066318/…

标签: java arrays


【解决方案1】:

这里是代码 sn-p 将 String 转换为 char 数组并以大写形式输出。

public static void main(String[] args)
    {
        String inputString;
        System.out.println("Please Enter the String");
        Scanner sc = new Scanner(System.in);
        inputString = sc.nextLine();
        sc.close();
        int len=inputString.length();
        char[] name = new char[len];
        for(int i =0; i < len; i++)
        {
            name[i] = inputString.toUpperCase().charAt(i);
        }
        System.out.println(name);
    }

【讨论】:

    【解决方案2】:

    这里是代码 sn-p 将 String 转换为 char[] 数组

        String input;
        Scanner keyboard = new Scanner(System.in);
        input = keybaord.nextLine();
        char[] nameChar = new char[input.length()];
        for(int i =0; i < name.length() ; i++)
        {
            nameChar[i] = name.charAt(i);
        }
        System.out.println(nameChar);
    

    【讨论】:

      猜你喜欢
      • 2019-08-29
      • 2022-07-07
      • 1970-01-01
      • 2021-01-20
      • 1970-01-01
      • 2015-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多