如何高效运用Java技巧移除字符串末尾多余的分隔符?
- 内容介绍
- 文章标签
- 相关推荐
本文共计2182个文字,预计阅读时间需要9分钟。
在中,直接输出结果:
考虑以下场景:我们有一个字符串列表,需要将它们连接起来,并在每个元素后添加一个逗号和空格。
public static ArrayList<String> getDropDownTextList(By locator) { // 假设 getDropDownOptions(locator) 返回 List<WebElement> // List<WebElement> countryList = getDropDownOptions(locator); // 这里我们模拟一个字符串列表 List<String> countryListText = new ArrayList<>(); countryListText.add("kushalhs"); countryListText.add("mayurvm"); countryListText.add("narendrabz"); StringBuilder combinedTextBuilder = new StringBuilder(); for(String text : countryListText) { // 原始代码中尝试 text.replace(',' , ' '); // 这通常用于替换字符串内部的字符,而不是移除末尾模式 // 如果是想移除每个元素文本中可能存在的逗号,这种用法是正确的 // 但如果目标是移除最终拼接字符串的末尾逗号,则不适用。
本文共计2182个文字,预计阅读时间需要9分钟。
在中,直接输出结果:
考虑以下场景:我们有一个字符串列表,需要将它们连接起来,并在每个元素后添加一个逗号和空格。
public static ArrayList<String> getDropDownTextList(By locator) { // 假设 getDropDownOptions(locator) 返回 List<WebElement> // List<WebElement> countryList = getDropDownOptions(locator); // 这里我们模拟一个字符串列表 List<String> countryListText = new ArrayList<>(); countryListText.add("kushalhs"); countryListText.add("mayurvm"); countryListText.add("narendrabz"); StringBuilder combinedTextBuilder = new StringBuilder(); for(String text : countryListText) { // 原始代码中尝试 text.replace(',' , ' '); // 这通常用于替换字符串内部的字符,而不是移除末尾模式 // 如果是想移除每个元素文本中可能存在的逗号,这种用法是正确的 // 但如果目标是移除最终拼接字符串的末尾逗号,则不适用。

