gpt4 book ai didi

java - 如何将从数据库中获取的结果转换为单个字符串?

转载 作者:行者123 更新时间:2023-11-30 03:25:21 27 4
gpt4 key购买 nike

我有从数据库获取标签的代码:

public void fetchTags() {  
ContentResolver contentResolver = this.getContentResolver();
Cursor cursor = contentResolver.query(TagsContentProvider.CONTENT_URI,
new String[]{Tags.COLUMN_TNAME}, null, null, null);
cursor.getCount();
while(cursor.moveToNext()) {
System.out.println(cursor.getString(cursor.getColumnIndex(Tags.COLUMN_TNAME)));
}
cursor.close();
}

输出:

enter image description here

如何将结果转换为单个字符串,其中字符以逗号分隔?

最佳答案

使用 StringBuilder :

// ...

final String SEPARATOR = ", ";

StringBuilder builder = new StringBuilder();
String prefix = "";

while(cursor.moveToNext()) {
builder.append(prefix);
prefix = SEPARATOR;
builder.append(cursor.getString(cursor.getColumnIndex(Tags.COLUMN_TNAME)));
}

String output = builder.toString()

// ...

StringBuilder 允许您比普通 outputString += inputString 更快地连接 String。这与 String 对象是不可变的,而 StringBuilder 则不然。如果您想了解更多信息,请查看例如在this article .

编辑:要将创建的字符串返回给调用方法,您的方法 fetchTags() 必须定义如下:

public String fetchTags() {

// your code

return output;

}

您使用返回类型void定义它:public void fetchTags() { ... }。这将不允许您返回任何值。

完整的方法 fetchTags() 应该如下所示:

public String fetchTags() {
ContentResolver contentResolver = this.getContentResolver();
Cursor cursor = contentResolver.query(TagsContentProvider.CONTENT_URI,
new String[] {
Tags.COLUMN_TNAME
}, null, null, null);
cursor.getCount();

final String SEPARATOR = ", ";

StringBuilder builder = new StringBuilder();
String prefix = "";

while (cursor.moveToNext()) {
builder.append(prefix);
prefix = SEPARATOR;
builder.append(cursor.getString(cursor.getColumnIndex(Tags.COLUMN_TNAME)));
}

String output = builder.toString()

cursor.close();

return output;
}

关于java - 如何将从数据库中获取的结果转换为单个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30361537/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com