有时我想将多个变量转换为字符串以通过消息或方法发送。
例如,如果我有这些变量:
int addressNum = 223;
String stName = "Main St";
String city = "Chicago";
我如何将其转换为单个字符串"223; Main St; Chicago"
并返回变量?
我会使用某种分隔符(, :)
String fullAddress+=addressNum+":"+stName+":"+city;
稍后,根据使用的分隔符拆分 fullAddress。
String[] arr = fullAddress.split(":");
int addressNumber = Integer.parseInt(arr[0]);
String streetName = arr[1];
String cityName = arr[2];
String oneLine = addressNum + "; " + stName + "; " + city; - make it in sinle line
// split it to variables below
String[] arr = oneLine.split(";");
addressNum = Integer.parseString(arr[0].trim());
stName = arr[1].trim();
city = arr[2].trim();
替代 String,编写一个保存数据的包装类:
public class SomeWrapper
{
int addressNum;
String stName;
String city;
// constructors, setters and getters
}
然后像这样使用它:
SomeWrapper w = new SomeWrapper(223, "Main St", "Chicago");
并像这样提取它:
int addressNum = w.getAddressNumber();
String stName = w.getStreetName();
String city = w.getCity();
并且您可以简单地将其传递给以下方法:
public static void doSomething(SomeWrapper w)
{
int addressNum = w.getAddressNumber();
// ...
}
// ...
public static void main(String[] args)
{
SomeWrapper w = ...;
doSomething(w);
}
您选择的编码必须是可逆的(双射)。
adress="value"
使用像JSon或ByteBuffer这样的标准可能是更好的做法。