在Java中删除第二个冒号后的字符串。

huangapple go评论75阅读模式
英文:

Remove string after second colon in Java

问题

我想要删除第二个冒号后的字符串,并在其后添加新的字符串。

当我点击一个标记时,我会在标记标题上使用AlertDialog添加字符串,以便我可以将这些值传递给处理文本文件的过程。但是,如果我再次选择该标记,我希望删除冒号后的文本,这样就不会再添加重复的字符串。

我查看了这个链接,但它使用了正则表达式,而我对此没有任何经验。

> 我的字符串 = W:3:ER1,ER2,ER3,,,,

> 输出 = W:3

我想要删除第二个冒号后的字符串,以便我可以附加我的字符串

这是我的onMarkerClick方法:

@Override
public boolean onMarkerClick(final Marker marker) {
    final String[] title = {marker.getTitle()};
    Bitmap smallDot = Bitmap.createScaledBitmap(getBitmapFromVectorDrawable(getApplicationContext(),
            R.drawable.blue_dot), 15, 15, false);

    final String[] selectedItems = {"", "", "", "", ""};

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setTitle("Enable Relays");

    // 添加复选框列表
    final String[] relays = {"Relay 1", "Relay 2", "Relay 3", "Relay 4", "Implement"};
    boolean[] checkedItems = {true, false, false, true, false};

    builder.setMultiChoiceItems(relays, null, new DialogInterface.OnMultiChoiceClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which, boolean isChecked) {

            if (isChecked) {
                // 如果用户勾选了项目,将其添加到所选项目中
                selectedItems[which] = "ER" + (which + 1);
            } else if (!isChecked) {
                // 否则,如果项目已经在数组中,将其删除
                selectedItems[which] = "";
            }
            Toast.makeText(MainActivity.this, "" + Arrays.toString(selectedItems), Toast.LENGTH_LONG).show();

        }
    }).setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

//            title[0] +=  ":" + selectedItems[0] + "," + selectedItems[1] + "," + selectedItems[2] + "," + selectedItems[3] + "," + selectedItems[4];

            int commas = 0;
            for (int i = 0; i < title[0].length(); i++) {
                if (title[0].charAt(i) == ',') commas++;
            }
            if (!title[0].contains("ER1") && commas <= 4)
                title[0] += ":" + selectedItems[0];
            if (!title[0].contains("ER2") && commas <= 4)
                title[0] += "," + selectedItems[1];
            if (!title[0].contains("ER3") && commas <= 4)
                title[0] += "," + selectedItems[2];
            if (!title[0].contains("ER4") && commas <= 4)
                title[0] += "," + selectedItems[3];
            if (!title[0].contains("ER5") && commas <= 4)
                title[0] += "," + selectedItems[4];

            marker.setTitle(title[0]);
            marker.showInfoWindow();
            Toast.makeText(MainActivity.this, "" + title[0], Toast.LENGTH_LONG).show();

        }
    }).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });

    // 创建并显示警告对话框
    AlertDialog dialog = builder.create();
    dialog.show();

    return true;
}
英文:

I would like to remove the string after the second colon and add a new string behind.

I have a maker when clicking on a marker I add the string using ALertDialog on the marker title so I can get those value to the process for a text file. But if I select that marker again I want to remove that text after colon so I don't add duplicate string again.

在Java中删除第二个冒号后的字符串。

I checked this link but it uses a regular expression and I don't have any experience with that.

> My String = W:3:ER1,ER2,ER3,,,,

>Output = W:3

I would like to remove the string after the second colon so I can attach my string

Here is my onMarkerClick

      @Override
public boolean onMarkerClick(final Marker marker) {
final String[] title = {marker.getTitle()};
Bitmap smallDot = Bitmap.createScaledBitmap(getBitmapFromVectorDrawable(getApplicationContext(),
R.drawable.blue_dot), 15, 15, false);
final String[] selectedItems = {&quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(&quot;Enable Relays&quot;);
// add a checkbox list
final String[] relays = {&quot;Relay 1&quot;, &quot;Relay 2&quot;, &quot;Relay 3&quot;, &quot;Relay 4&quot;, &quot;Implement&quot;};
boolean[] checkedItems = {true, false, false, true, false};
builder.setMultiChoiceItems(relays, null, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
selectedItems[which] = &quot;ER&quot; + (which + 1);
} else if (!isChecked) {
// Else, if the item is already in the array, remove it
selectedItems[which] = &quot;&quot;;
}
Toast.makeText(MainActivity.this, &quot;&quot; + Arrays.toString(selectedItems), Toast.LENGTH_LONG).show();
}
}).setPositiveButton(&quot;OK&quot;, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//                title[0] +=  &quot;:&quot; + selectedItems[0] + &quot;,&quot; + selectedItems[1] + &quot;,&quot; + selectedItems[2] + &quot;,&quot; + selectedItems[3] + &quot;,&quot; + selectedItems[4];
int commas = 0;
for (int i = 0; i &lt; title[0].length(); i++) {
if (title[0].charAt(i) == &#39;,&#39;) commas++;
}
if (!title[0].contains(&quot;ER1&quot;) &amp;&amp; commas &lt;= 4)
title[0] += &quot;:&quot; + selectedItems[0];
if (!title[0].contains(&quot;ER2&quot;) &amp;&amp; commas &lt;= 4)
title[0] += &quot;,&quot; + selectedItems[1];
if (!title[0].contains(&quot;ER3&quot;) &amp;&amp; commas &lt;= 4)
title[0] += &quot;,&quot; + selectedItems[2];
if (!title[0].contains(&quot;ER4&quot;) &amp;&amp; commas &lt;= 4)
title[0] += &quot;,&quot; + selectedItems[3];
if (!title[0].contains(&quot;ER5&quot;) &amp;&amp; commas &lt;= 4)
title[0] += &quot;,&quot; + selectedItems[4];
marker.setTitle(title[0]);
marker.showInfoWindow();
Toast.makeText(MainActivity.this, &quot;&quot; + title[0], Toast.LENGTH_LONG).show();
}
}).setNegativeButton(&quot;CANCEL&quot;, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
return true;
}

答案1

得分: 0

首先我们在最后一个 : 处进行分割,以获取标题。
然后我们在最后一个 : 后面的 , 处进行解析,以获取项目,并过滤掉空项目。

import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        String raw = "W:3:ER1,ER2,ER3,,,,";
        String title = raw.substring(0, raw.lastIndexOf(":"));
        String[] selectedItems = raw.substring(raw.lastIndexOf(":")+1).split(",");
        List<String> items = Arrays.asList(selectedItems).stream().filter(str ->
            ! "".equals(str)
        ).collect(Collectors.toList());

        System.out.println("Title " + title);
        System.out.println("Items " + items);
    }
}

输出结果为:

Title W:3
Items [ER1, ER2, ER3]

编辑 1:应处理单个冒号

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        String raw = "W:3";
        List<String> items;
        String title;
        if (raw.replaceAll("[^:]", "").length() > 1) { // 含有多个冒号的字符串
            title = raw.substring(0, raw.lastIndexOf(":"));
            String[] selectedItems = raw.substring(raw.lastIndexOf(":") + 1).split(",");
            items = Arrays.asList(selectedItems).stream().filter(str ->
                    !"".equals(str)
            ).collect(Collectors.toList());
        } else {
            title = raw;
            items = null;
        }

        System.out.println("Title " + title);
        System.out.println("Items " + items);
    }
}

对于 raw = "W:3"; 的情况,输出为:

Title W:3
Items null

英文:

First we split on the last : to get the title.
Then we parse on , from the last : to get items and we filter out empty ones.

import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        String raw = &quot;W:3:ER1,ER2,ER3,,,,&quot;;
        String title = raw.substring(0, raw.lastIndexOf(&quot;:&quot;));
        String[] selectedItems = raw.substring(raw.lastIndexOf(&quot;:&quot;)+1).split(&quot;,&quot;);
        List&lt;String&gt; items = Arrays.asList(selectedItems).stream().filter(str -&gt;
            ! &quot;&quot;.equals(str)
        ).collect(Collectors.toList());


        System.out.println(&quot;Title &quot;+ title);
        System.out.println(&quot;Items &quot;+ items);
    }
}

Prints
> Title W:3
Items [ER1, ER2, ER3]

Edit 1 : Should handle single colon

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        String raw = &quot;W:3&quot;;
        List&lt;String&gt; items;
        String title;
        if (raw.replaceAll(&quot;[^:]&quot;, &quot;&quot;).length() &gt; 1) { // String with every :
            title = raw.substring(0, raw.lastIndexOf(&quot;:&quot;));
            String[] selectedItems = raw.substring(raw.lastIndexOf(&quot;:&quot;) + 1).split(&quot;,&quot;);
            items = Arrays.asList(selectedItems).stream().filter(str -&gt;
                    !&quot;&quot;.equals(str)
            ).collect(Collectors.toList());
        } else {
            title = raw;
            items = null;
        }


        System.out.println(&quot;Title &quot;+ title);
        System.out.println(&quot;Items &quot;+ items);
    }
}

And prints for raw = &quot;W:3&quot;;
> Title W:3
Items null

答案2

得分: 0

I found the trick to remove string after the second colon.

First, find the position for the second colon. Then remove the string after that position.

Here the method for finding the position

    private static int findSecondColonPosition(String s) {
            int result = -1;
            int colonsToFind = 2;
            char[] ca = s.toCharArray();
            for (int i = 0; i < ca.length; ++i) {
                if (ca[i] == ':') --colonsToFind;
                if (colonsToFind == 0) return i;
            }
            return result;
        }


Here my updated **onMarkerClick** code 

        @Override
        public boolean onMarkerClick(final Marker marker) {
            final String[] title = {marker.getTitle()};
            Bitmap smallDot = Bitmap.createScaledBitmap(getBitmapFromVectorDrawable(getApplicationContext(),
                    R.drawable.blue_dot), 15, 15, false);
    
            final String[] selectedItems = { "", "", "", ""};
    
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("Enable Relays");
    
            // add a checkbox list
            final String[] relays = {"Relay 2", "Relay 3", "Relay 4", "Implement"};
    
            builder.setMultiChoiceItems(relays, null, new DialogInterface.OnMultiChoiceClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which, boolean isChecked) {
    
                    if (isChecked) {
                        // If the user checked the item, add it to the selected items
                        selectedItems[which] = "ER" + (which + 2);
                    } else if (!isChecked) {
                        // Else, if the item is already in the array, remove it
                        selectedItems[which] = "";
                    }
                    Toast.makeText(MainActivity.this, "" + Arrays.toString(selectedItems), Toast.LENGTH_LONG).show();
    
                }
            }).setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
    
                    int secondColonPosition = findSecondColonPosition(title[0]);
    
                    if (secondColonPosition > 0) {
                        System.out.println("title after remove: " + title[0].substring(0, secondColonPosition));
                        title[0] = title[0].substring(0, secondColonPosition);
                    } else {
                        System.out.println("ERROR: there is not a 2nd colon in " + title[0]);
                    }
    
                    title[0] += ":" + selectedItems[0] + "," + selectedItems[1] + "," + selectedItems[2] + "," + selectedItems[3];
    
                    marker.setTitle(title[0]);
                    marker.showInfoWindow();
                    Toast.makeText(MainActivity.this, "" + title[0], Toast.LENGTH_LONG).show();
    
                }
            }).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
    
                }
            });
    
            // create and show the alert dialog
            AlertDialog dialog = builder.create();
            dialog.show();
    
            return true;
        }
英文:

I found the trick to remove string after the second colon.

First, find the position for the second colon. Then remove the string after that position.

Here the method for finding the position

private static int findSecondColonPosition(String s) {
int result = -1;
int dotsToFind = 2;
char[] ca = s.toCharArray();
for (int i = 0; i &lt; ca.length; ++i) {
if (ca[i] == &#39;:&#39;) --colonsToFind;
if (dotsToFind == 0) return i;
}
return result;
}

Here my updated onMarkerClick code

    @Override
public boolean onMarkerClick(final Marker marker) {
final String[] title = {marker.getTitle()};
Bitmap smallDot = Bitmap.createScaledBitmap(getBitmapFromVectorDrawable(getApplicationContext(),
R.drawable.blue_dot), 15, 15, false);
final String[] selectedItems = { &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(&quot;Enable Relays&quot;);
// add a checkbox list
final String[] relays = {&quot;Relay 2&quot;, &quot;Relay 3&quot;, &quot;Relay 4&quot;, &quot;Implement&quot;};
builder.setMultiChoiceItems(relays, null, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
selectedItems[which] = &quot;ER&quot; + (which + 2);
} else if (!isChecked) {
// Else, if the item is already in the array, remove it
selectedItems[which] = &quot;&quot;;
}
Toast.makeText(MainActivity.this, &quot;&quot; + Arrays.toString(selectedItems), Toast.LENGTH_LONG).show();
}
}).setPositiveButton(&quot;OK&quot;, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int secoundColonPosition = findSecondColonPosition(title[0]);
if (secoundColonPosition &gt; 0) {
System.out.println(&quot;title after remove: &quot; + title[0].substring(0, secoundColonPosition));
title[0] = title[0].substring(0, secoundColonPosition);
} else {
System.out.println(&quot;ERROR: there is not a 2nd colon in &quot; + title[0]);
}
title[0] += &quot;:&quot; + selectedItems[0] + &quot;,&quot; + selectedItems[1] + &quot;,&quot; + selectedItems[2] + &quot;,&quot; + selectedItems[3];
marker.setTitle(title[0]);
marker.showInfoWindow();
Toast.makeText(MainActivity.this, &quot;&quot; + title[0], Toast.LENGTH_LONG).show();
}
}).setNegativeButton(&quot;CANCEL&quot;, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
//        if (isEnable()) {
//            title += &quot;:Enable_Implement&quot;;
//            marker.setTitle(title);
//            marker.setIcon(BitmapDescriptorFactory.fromBitmap(smallDot));
//            setEnable(false);
//            setDisable(true);
//            programStatusTextView.setText(&quot;Choose a stop actuation point&quot;);
//        } else if (isDisable()) {
//            title += &quot;:Disable_Implement&quot;;
//            marker.setTitle(title);
//            marker.setIcon(BitmapDescriptorFactory.fromBitmap(smallDot));
//            setDisable(false);
//            programStatusTextView.setText(&quot;&quot;);
//        }
return true;
}

huangapple
  • 本文由 发表于 2020年9月24日 21:44:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/64047835.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定