java中字符串和字符数组的区别?

Python011

java中字符串和字符数组的区别?,第1张

字符串以\0结束那是字符串在计算机内的存储结构,你定义了字符串计算机默认会在字符串后加上\0做为字符串结束标记,但是你写程序时并没有显式的写出来。

判断是否为字符串:字符串都是用双引号包含的。例如char *string="beijing"。

定义字符串有两种方法:一、字符串指针 char *string="abcde"

二、一维字符数组。例如:char string[10]string="abcde"

用字符数组定义注意了,数组长度为n,但是字符个数只能为n-1,就是上面说的计算机默认加了\0占了一个,否则会溢出。

字符数组一维的和字符串一样,二维的就是char string[M][N]当然你还可以类似定义多维的。

比较的规则和数据库中的order by效果一致

实现代码如下

/**

* Name: 比较两个字符串大小

* null自动转为空,空字符串最大;

*

* @param first 要比较的第一个字符串;

* second 要比较的第二个字符串;

* @return first大于second返回正数;

*first等于second返回0;

* first小于second返回负数;

* 内部异常默认返回0;

* 返回值非固定值;

*/

public static int compareString(String first,String second){

int result = 0

try{

//null转空

first = first==null?"":first

second = second==null?"":second

//预先记录字符串长度,避免反复读取

int firstLength=first.length()

int secondLength=second.length()

//处理含有空串的特殊情况

if("".equals(first) || "".equals(second)){

//谁长谁小

result = secondLength-firstLength

}else{

//临时空间,用来存放ascii码总和

int firstCount = 0

int secondCount = 0

//用纯运算得出两个数中较小的数,实在是bt

int minLength = (secondLength*(firstLength/secondLength) +

firstLength*(secondLength/firstLength))/(firstLength/secondLength +

secondLength/firstLength)

//按两个字符串中较短的位数去逐位截取,防止越界

for(int i=0i<minLengthi++){

//求ascii码和

firstCount+=first.substring(i,i+1).getBytes()[0]

secondCount+=second.substring(i,i+1).getBytes()[0]

//和不相等,说明已经比较出了大小

if(firstCount!=secondCount){

break

}

}

if(firstCount==secondCount){

//长度长的大

result = firstLength-secondLength

}else{

//总和大的大

result = firstCount-secondCount

}

}

}catch (Exception e) {}

return result

}