String字串位置移動

來源:互聯網
上載者:User

標籤:string   slist   int   定義   number   target   proc   asm   sso   

有規律的String字串位置移動

1.自訂一個有規律的String字串

String numstr = "1,2,3,x,y,4,5";

2.按逗號拆分numstr字串

String[] nums = numstr.split(",");

3.將nums數組轉為list

List<String> numlist = Arrays.asList(nums);

4.擷取list中x的下標 此處index為:3

int index = numlist.indexOf("x");

5.將x向後移動一位

Collections.rotate(numlist.subList(index, index+1+1), -1);

6.將list轉為String字串  此處輸出numstr為:1,2,3,y,x,4,5

numstr = String.join(",", numlist);

 7.rotate方法的使用

Rotate方法需要一個參數distance,該方法將一個List旋轉多少長度為distance。假如有個序列列list[a,b,c,d],調用方法Collections.rotate(list, 1)後,得到的list就變為了[d,a,b,c]。 
調用此方法後,位置i上的元素將變為位置(i - distance) mod list.size()的元素,0 <= i < list.size()distance可以為正數、0、負數。正數代表向前(下標值變大的方向)旋轉,負數代表向後旋轉。調用方法Collections.rotate(list, -1)後,得到的list就變為了[b,c,d,a]

這個方法常常和ListsubList方法結合使用,用於將一個list的某個或多個元素進行移動,而不破壞其餘元素的順序。例如為了將某個list的位置j的元素向前移動到k的位置。(設移動的距離為dd >= 0),k = j + d + 1)。

Collections.rotate(list.subList(j, k+1), -1);

舉個栗子,例如[a,b,c,d,e],將b元素向前移動三個位置

Collections.rotate(list.subList(1, 5), -1);

   調用後得到list[a,c,d,e,b]

8.rotate詳解

52891183

String字串位置移動

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.