關於substring的char[]共用,substringchar共用

來源:互聯網
上載者:User

關於substring的char[]共用,substringchar共用

我們知道,對於一個較大的String對象如果從中擷取一個子串,jdk預設子串的char[]是共用原串的char[],即子串的char[]是原串的char[]中的一部分,

這樣對於一個原串多個子串的情況可以節省很大空間。

但是也正是因為共用,如果一個很大的原串在擷取一個很小的子串後,原串不再需要,卻因為子串共用了char[]一直不能釋放,在很多時候造成相反

的結果,甚至出現效能上的問題:

參見:https://code.google.com/p/mybatis/issues/detail?id=760

要解決這種情況 ,在jdk6中,我們只能在擷取子串後重新new一個子串的新串使用,以使原串的char[]不再被引用從而快速釋放:

String src = "abcdefghijklmnopqrstuvwxyz1234567890-=";String sub = src.substring(1,4);sub = new String(sub);

...................................

use sub

這樣的方式代碼晦澀,問題難查。jdk7去掉共用,同時jdk7最佳化了拷貝,利用cpu的simd指令。大部分情境下,jdk7字串效能是比jdk6好的:

 1950       public String substring(int beginIndex, int endIndex) { 1951           if (beginIndex < 0) { 1952               throw new StringIndexOutOfBoundsException(beginIndex); 1953           } 1954           if (endIndex > count) { 1955               throw new StringIndexOutOfBoundsException(endIndex); 1956           } 1957           if (beginIndex > endIndex) { 1958               throw new StringIndexOutOfBoundsException(endIndex - beginIndex); 1959           } 1960           return ((beginIndex == 0) && (endIndex == count)) ? this : 1961               new String(offset + beginIndex, endIndex - beginIndex, value); 1962       }



編寫函數substring(char s[], char sub[]),找字串sub在字串s中第一次出現的下標位置,如未找到,返回-1

#include<iostream.h>
int Strfind(char *s,char *t)
{
int index,lengths=0,lengtht=0,i,j;
char * Position;
while(s[lengths]!=0)//擷取字串s的長度
{
lengths++;
}
while(t[lengtht]!=0)
{
lengtht++;
}
for(i=0;i<lengths-lengtht;i++)//迴圈到源串的長度減去目標串的長度即可
{
index=0;
while(s[i+index]==t[index] && index<lengtht)
{
index++;
}
if(index==lengtht)
{
// Position=new char;
// *Position=i;
// return Position;
return i;//返回i的位置既是找到的位置
}
}
//Position=NULL;
return -1;//找不到
}
int main()
{
char str1[500];
char str2[500];
cin>>str1;
cin>>str2;
// char * Position=Strfind(str1,str2);
// cout<<*Position<<endl;
cout<<Strfind(str1,str2)<<endl;
return 0;
}
 
怎用C語言實現一個字串的截取 函數原型是這樣的char *subString(char *str,int star,int len);

char *subString(char *str,int star,int len);

這個原型不好,返回的子串放到什麼地方呢?
i.如果用malloc分配的話,函數調用者忘記free就會有記憶體泄露
ii.如果放到源串,就會破環源串

char *subString(char *dst,char *src,int star,int len);
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.