开发者

How to split a string into half in android?

开发者 https://www.devze.com 2023-03-01 12:48 出处:网络
I have a string i want to split it into half? 开发者_高级运维String Data = \"This is a string\"

I have a string i want to split it into half?

开发者_高级运维
String Data = "This is a string"

This is an example string. In the real case i will not know what is inside the string, how long it is etc


String data = "This is a string";
String half1 = data.subString(0, data.length() / 2);
String half2 = data.subString(data.length()/2);

Also, remember that Strings are immutable, you can't just call data.subString(data.length()/2); and expect that data will be changed. You have to assign the returned String to some variable (as in my example).


If you want to use substring then you can do like this:

String val1 = data.substring(0, data.length()/2);
String val2 = data.substring(data.length()/2);

It's a common logic that if you want exact half then split it by its-length/2.

Also, don't start variable name with capital letter.

0

精彩评论

暂无评论...
验证码 换一张
取 消