java如何刪除以逗號隔開的字符串中某一個值
刪除以逗號隔開的字符串中某一個值
例如要刪除 “1,2,3,4” 中的 2,返回 “1,3,4”
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class test {
public static void main(String[] args) {
String str="1,2,3,4"; //原字符串
String newStr=""; //新字符串
String[] array=str.split(","); //字符串轉(zhuǎn)數(shù)組
List<String> list= Arrays.asList(array);
List<String> arrList = new ArrayList<String>(list); //字符串轉(zhuǎn)集合
arrList.remove("2"); //要刪除的元素
String[] strings = new String[arrList.size()]; //再將集合轉(zhuǎn)為數(shù)組
String[] newArray = arrList.toArray(strings);
//遍歷數(shù)組,插入逗號
for(int j=0;j<newArray.length;j++){
newStr+=newArray[j]+",";
}
if(!"".equals(newStr)){ //如果刪完之后字符串不為空
newStr=newStr.substring(0, newStr.length()-1); //刪除最后的逗號
}
System.out.println(newStr);
}
}輸出結(jié)果

移除以逗號分隔的字符串中指定元素
封裝的一個小方法。
適用場景
如有個字段用來存儲多個用戶 ID,并且是以逗號分隔的,例:1,2,3,現(xiàn)要移除指定的某個 ID
核心代碼
/*
? ? ?* @ClassName Test
? ? ?* @Desc TODO ? 移除指定用戶 ID
? ? ?* @Date 2019/8/31 14:58
? ? ?* @Version 1.0
? ? ?*/
? ? public static String removeOne(String userIds, Long userId) {
? ? ? ? // 返回結(jié)果
? ? ? ? String result = "";
? ? ? ? // 判斷是否存在。如果存在,移除指定用戶 ID;如果不存在,則直接返回空
? ? ? ? if(userIds.indexOf(",") != -1) {
? ? ? ? ? ? // 拆分成數(shù)組
? ? ? ? ? ? String[] userIdArray = userIds.split(",");
? ? ? ? ? ? // 數(shù)組轉(zhuǎn)集合
? ? ? ? ? ? List<String> userIdList = new ArrayList<String>(Arrays.asList(userIdArray));
? ? ? ? ? ? // 移除指定用戶 ID
? ? ? ? ? ? userIdList.remove(userId.toString());
? ? ? ? ? ? // 把剩下的用戶 ID 再拼接起來
? ? ? ? ? ? result = StringUtils.join(userIdList, ",");
? ? ? ? }
? ? ? ? // 返回
? ? ? ? return result;
? ? }測試驗證
直接 main 里面跑一下
// 傳入的所有用戶 ID
String userIds = "1,2,3";
// 遍歷移除用戶 ID,并打印到控制臺
for(int i = 1 ; i <= 3; i++) {
? System.out.println(userIds = removeOne(userIds, Long.parseLong(String.valueOf(i))));
}控制臺輸出結(jié)果
2,3
3
方法寫的很簡單,用于字符串能確保正規(guī)的情況是足夠了;當然也可以根據(jù)具體的業(yè)務場景來改善邏輯,使代碼更加完美。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
如何更優(yōu)雅地獲取spring boot yml中的值
這篇文章主要給大家介紹了關于如何更優(yōu)雅地獲取spring boot yml中值的相關資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用spring boot具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧2019-06-06
SpringCloud_Sleuth分布式鏈路請求跟蹤的示例代碼
Spring Cloud Sleuth是一款針對Spring Cloud的分布式跟蹤工具,本文通過實例代碼介紹了SpringCloud_Sleuth分布式鏈路請求跟蹤,感興趣的朋友跟隨小編一起看看吧2023-02-02
SpringBoot基于Mybatis-Plus自動代碼生成
這篇文章主要介紹了SpringBoot基于Mybatis-Plus自動代碼生成,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-04-04
MyBatis-Plus通用枚舉自動關聯(lián)注入的實現(xiàn)
本文主要介紹了MyBatis-Plus通用枚舉自動關聯(lián)注入的實現(xiàn),解決了繁瑣的配置,讓 mybatis 優(yōu)雅的使用枚舉屬性,感興趣的可以一起來了解一下2021-06-06

