简体   繁体   English

如何从字符串中删除结尾字符

[英]How to remove trailing character(s) from a string

I have a file which contains a data structure. 我有一个包含数据结构的文件。 The data is stored as bytes. 数据存储为字节。 I want to display a data (name of person) to screen. 我想显示要显示的数据(人名)。 Size of the name is about 12 characters long. 名称的大小约为12个字符。 But data may be less than or equal to 12 characters. 但是数据可能少于或等于12个字符。 I converted the byte array to string and display data. 我将字节数组转换为字符串并显示数据。 when tried to display data using system.out.println method, it shows data plus unwanted characters. 当尝试使用system.out.println方法显示数据时,它将显示数据以及不需要的字符。 How to show only wanted data. 如何仅显示所需数据。

i tried with below code 我尝试下面的代码

// here Name is a byte array
title = new String( Name );
System.out.println("Title = " + title);

output i received is 我收到的输出是

    Title = area1����������

i want only 'area1'. 我只想要'area1'。 please provide a solution to resolve it 请提供解决方案

    String title = new String( Name ,"UTF-8" );
    System.out.println("Title = " + title);
System.out.println("Title = area1����������".replaceAll("([^A-Za-z0-9 ])", ""));

give : Title area1 , you can also add .replaceAll("\\ \\ "," ")); 给定: Title area1 ,还可以添加.replaceAll("\\ \\ "," ")); or tune the regex as you like 或根据需要调整正则表达式

你有没有尝试过?

String decoded = new String(Name, "UTF-8"); 

from How to determine whether a character is a letter in Java? from 如何确定一个字符在Java中是否是字母?

string.matches("\\p{L}"); // Unicode letter
string.matches("\\p{Lu}"); // Unicode upper-case letter

You can also do this with Character class: 您也可以使用Character类执行此操作:

Character.isLetter(character);

but that is less convenient if you need to check more than one letter. 但这不方便,如果您需要检查多个字母。

Using the StringBuilder class, build up the string by appending each character that is read from input file stream, until the end of file is reached. 使用StringBuilder类,通过附加从输入文件流读取的每个字符来构建字符串,直到到达文件末尾。 Once end of file is reached, then immediately return back the string via the toString() method of the StringBuilder class. 到达文件末尾后,立即通过StringBuilder类的toString()方法返回该字符串。

StringBuilder sb = new StringBuilder();
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");//
int c = 0;
while ((c = isr.read()) != -1) {
    sb.append((char) c);
}
String fixedString = sb.toString();

find the updated code here: 在此处找到更新的代码:

        // here Name is a byte array
    String title = new String( "area1����������");
    System.out.println("Title = " + title);

    StringBuilder sb = new StringBuilder(title);
    StringBuilder sb2 = new StringBuilder();
    for(int i=0;i<sb.length();i++)
    {
        if(Character.isLetterOrDigit(sb.charAt(i)))
        {
            sb2.append(sb.charAt(i));
        }
    }

    title = sb2.toString();
    System.out.println("Title = " + title);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM