我有一个字符串2.0.0.3和一个int值4
更新字符串的最简单方法是什么,如2.0.0.4。
尝试使用StringBuilder
和chatAt
StringBuilder myName = new StringBuilder(name);
myName.setCharAt(3,(char) value);
然而,myname的sysout给出了一个正方形而不是2004年。
答案 0 :(得分:0)
应该是
StringBuilder myName = new StringBuilder(name); myName.setCharAt(6,(char) ('0'+value));
(顺便说一句,这是相当糟糕的风格,我相信其他人会提出更清洁的解决方案。)
答案 1 :(得分:0)
尝试
char replacementChar = (char) ('0' + value);
StringBuilder myName = new StringBuilder(name);
myName.setCharAt(6,replacementChar);
但是,我建议使用其他技术来更新该字符串吗?
使用类对其进行建模并通过实现toString()完全构建它应该更明智。
public class Version {
private final static String SEPARATOR = ".";//Note separator could be a field instead of a contant
private int major;
private int minor;
private int incremental;
private int buildVersion;
public Version(int major, int minor, int incremental, int buildVersion) {
this.major = major;
this.minor = minor;
this.incremental = incremental;
this.buildVersion = buildVersion;
}
/**
* Populates this class from String
* @param version a version number made of numbers separated by a dot
*/
public Version(String version) {
if(version != null){
String[] numbers = version.split("\\" + SEPARATOR);
if(numbers.length>0) major = toInt(numbers[0]);
if(numbers.length>1) minor = toInt(numbers[1]);
if(numbers.length>2) incremental = toInt(numbers[2]);
if(numbers.length>3) buildVersion = toInt(numbers[3]);
}
}
private int toInt(String strVal){
int val = 0;
try {
val = Integer.parseInt(strVal);
} catch (NumberFormatException ex) {
// TODO replace this, please
ex.printStackTrace();
}
return val;
}
/**
* @return the major
*/
public int getMajor() {
return major;
}
/**
* @param major the major to set
*/
public void setMajor(int major) {
this.major = major;
}
/**
* @return the minor
*/
public int getMinor() {
return minor;
}
/**
* @param minor the minor to set
*/
public void setMinor(int minor) {
this.minor = minor;
}
/**
* @return the incremental
*/
public int getIncremental() {
return incremental;
}
/**
* @param incremental the incremental to set
*/
public void setIncremental(int incremental) {
this.incremental = incremental;
}
/**
* @return the buildVersion
*/
public int getBuildVersion() {
return buildVersion;
}
/**
* @param buildVersion the buildVersion to set
*/
public void setBuildVersion(int buildVersion) {
this.buildVersion = buildVersion;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return major + SEPARATOR + minor + SEPARATOR + incremental + SEPARATOR + buildVersion;
}
}
这个类可以这样使用:
Version version = new Version("2.0.0.3");//could be new Version(2, 0, 0, 3)
version.setBuildVersion(4);
System.out.println(version);