Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/383.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java字符串操作-编写高效代码_Java_Android_String - Fatal编程技术网

Java字符串操作-编写高效代码

Java字符串操作-编写高效代码,java,android,string,Java,Android,String,首先,我不是一个有经验的java开发人员。问题是我的sql查询返回的数据如下ABC BCD DEF EFG。但是,我想在每个条目之后添加,,所以我尝试了这个 if (cursor != null) { cursor.moveToFirst(); do { if (cursor.getPosition() == 0) { getName = cursor.getString(

首先,我不是一个有经验的java开发人员。问题是我的sql查询返回的数据如下
ABC BCD DEF EFG
。但是,我想在每个条目之后添加
,所以我尝试了这个

if (cursor != null) {
            cursor.moveToFirst();
            do {

                if (cursor.getPosition() == 0) {

                    getName = cursor.getString(cursor.getColumnIndexOrThrow("NAME"));

                } else {

                    getName = getName + ","
                            + cursor.getString(cursor.getColumnIndexOrThrow("NAME"));
                }

            } while (cursor.moveToNext());
        }
我的问题是,这可以吗,或者有什么方法可以有效地编写此代码(比如通过编写更少的代码行来实现相同的目标)。谢谢。

这个怎么样:

myString = "ABC BCD DEF EFG";
String newString = myString.replace(" ", ", ");
System.out.println(newString);
输出:

ABC, BCD, DEF, EFG

使用MySql查询本身包含逗号怎么样?你可以在链接中找到更多关于它的信息

下面的代码会更短,应该与您发布的代码完全相同

if (cursor != null) {
    cursor.moveToFirst();
    getName = cursor.getString(cursor.getColumnIndexOrThrow("NAME"));
    while (cursor.moveToNext()) {
        getName = getName + "," + cursor.getString(cursor.getColumnIndexOrThrow("NAME"));
    }
}
怎么样-

String str = "ABC BCD DEF EFG";
str = str.replaceFirst(" ", ", ");
System.out.println(str);
输出:

ABC, BCD, DEF, EFG
ABC,BCD DEF EFG


您可以用更少的代码完成这项工作,但其效率可能不会更高:

if (cursor != null) {
    cursor.moveToFirst();
    while(cursor.moveToNext()) {
        getName += ((!"".equals(getName))?",":"") + cursor.getString(cursor.getColumnIndexOrThrow("NAME"));
    } 
}

根据您的要求,您可以在实际查询中使用concat。

如果在生成结果时使用
StringBuilder
而不是
String
,您的代码将更加高效

StringBuilder str = new StringBuilder();
loop...
    if (first) {
        str.append(cursor.getString(...));
    } else {
        str.append(',');
        str.append(cursor.getString(...));
    }
String theString = str.toString();

每次使用带字符串的
+
时,在场景后面都会创建需要垃圾收集的临时对象。通过显式使用
StringBuilder
可以完全避免在循环的每次迭代中生成字符串时使用额外的对象。

我想指出代码中的一个问题(与字符串格式无关)。当光标指向第一条记录时,应始终检查null

if (cursor.moveToFirst() != null)
{
    ...
}

那不是和你真正想要的相反吗?我不明白你的意思@RohitJainI的意思是,您的代码当前将在除第一个元素之外的所有元素后面添加逗号。但你想要的恰恰相反。仅在第一个元素后添加逗号。检查您当前的代码是否工作正常。@RohitJain-Nope。它工作并返回ABC、BCD、DEF、,EFG@RohitJain也许是你没有理解我。请检查我最后的评论。这就是我想要的格式。阅读他的评论,我想他会想要
replaceAll
,但这是实现他要求的IMO+1的最佳答案,所以我认为“ABC”、“BCD”等只是例子。实际字符串可能包含不应替换的空格。