【问题标题】:how to extract specific characters from a string如何从字符串中提取特定字符
【发布时间】:2014-08-31 20:00:29
【问题描述】:

我正在从事一个项目,我必须从文件中读取数据并将该数据存储到字符串数组中。

字符串数组位置“0”应包含文件的前 13 个字符,字符串数组位置“1”应包含文件的后 13 个字符。 我尝试使用 getchar() 仅读取前 13 个字符,但我无法使用它,谁能指出我的错误,因为当我尝试在应用程序上运行它时,应用程序崩溃了。

   InputStream is = getResources().openRawResource(R.raw.temp);
   BufferedReader br = new BufferedReader(new InputStreamReader(is));
            try {

                while((string = br.readLine()) != null){
                string.getChars(0,13, buffer, 0);
                    String str = new String(buffer);
                    text.setText(str);  

                }

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            break;

这里的buffer是一个char类型的数组。

【问题讨论】:

  • 所需的语言是什么?
  • 是Java还是什么?
  • 是的,它的 java,我正在做 android 编程,我是新手。

标签: java char bufferedreader getchar


【解决方案1】:

使用String.substring(startIndex, endIndex) 检索字符串的一部分。

【讨论】:

    【解决方案2】:

    当您尝试将字符串拆分为 13 个字符的块时,为什么要使用 readLine?

    String str = "Some string that may or may not be longer than 13 characters";
    int LENGTH = 13, off_multiplier = 0, read_size;    
    char [] buffer = new char[LENGTH];
    
    ArrayList<String> string_array = new ArrayList<String>();
    
    InputStream is = new ByteArrayInputStream(str.getBytes());
    try(BufferedReader reader = new BufferedReader(new InputStreamReader(is))){
        while( (read_size = reader.read(buffer, off_multiplier * LENGTH ,LENGTH)) != -1){
            string_array.add(new String(buffer,0,read_size));
        }
    }
    

    【讨论】:

    • @Asad 这是你要拆分的字符串,好像我在复制粘贴时遗漏了它,已修复。
    • @Asad 那是你想要的吗?如果是,请将其标记为答案,以便其他人知道。
    猜你喜欢
    • 1970-01-01
    • 2015-06-07
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2017-07-28
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多