将ByteBuffer转换为字符串,删除位于字符串末尾的换行符?

huangapple go评论140阅读模式
英文:

Converting ByteBuffer To String remove linebreaks of string which are located at the end of String?

问题

以下是您在Android Studio中编写的代码的翻译:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String hello = "Hello\n\n";
        ByteBuffer buffer2 = ByteBuffer.allocate(hello.getBytes().length);
        buffer2.put(hello.getBytes());
        buffer2.flip();
        while (true) {
            Log.d(TAG, new String(buffer2.array()));
        }
    }
}

它应该打印带有换行的"Hello",但如下面的截图所示,实际上没有打印出换行。

英文:

I write the following code in the android studio

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String hello = "Hello\n\n";
        ByteBuffer buffer2 = ByteBuffer.allocate(hello.getBytes().length);
        buffer2.put(hello.getBytes());
        buffer2.flip();
        while (true) {
            Log.d(TAG, new String(buffer2.array()));
        }
    }
}

It should print Hello with line breaks but as shown in the following screenshot it doesn't.将ByteBuffer转换为字符串,删除位于字符串末尾的换行符?

答案1

得分: 1

Demo:

import java.nio.ByteBuffer;

public class Main {
    public static void main(String[] args) {
        String hello = "Hello\n\n";
        ByteBuffer buffer2 = ByteBuffer.allocate(hello.getBytes().length);
        buffer2.put(hello.getBytes());
        buffer2.flip();

        System.out.println(new String(buffer2.array()) + "Hi");
    }
}

Output:

Hello

Hi
英文:

> Converting ByteBuffer To String remove linebreaks of string which are
> located at the end of String?

Answer: No


Demo:

import java.nio.ByteBuffer;

public class Main {
	public static void main(String[] args) {
		String hello = "Hello\n\n";
		ByteBuffer buffer2 = ByteBuffer.allocate(hello.getBytes().length);
		buffer2.put(hello.getBytes());
		buffer2.flip();

		System.out.println(new String(buffer2.array()) + "Hi");
	}
}

Output:

Hello

Hi

huangapple
  • 本文由 发表于 2020年7月24日 21:49:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/63074942.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定