java c 字符串_字符串处理java与c的对比

5.字符串

public class World {

public static void main(String[] args) {

// TODO 自动生成的方法存根

String name ="Tom";

String sex ="Felmale";

String from ="USA";

String info1="name:"+name+"   sex:"+sex+"  from:"+from;

String info2="name:"+name+"\n"+"sex:"+sex+"\n"+"from:"+from;

System.out.println("info1");

System.out.println("info2");

}

此程序输出info1,info2;

public class World {

public static void main(String[] args) {

// TODO 自动生成的方法存根

String name ="Tom";

String sex ="Felmale";

String from ="USA";

String info1="name:"+name+"   sex:"+sex+"  from:"+from;

String info2="name:"+name+"\n"+"sex:"+sex+"\n"+"from:"+from;

System.out.println(info1);

System.out.println(info2);

}

这个程序输出:

name:Tom   sex:Felmale  from:USA

name:Tom

sex:Felmale

from:USA

(此处有一行)

如果加引号,打印处字符串常量“info1”而不是把它当变量处理,不加引号输出info1的赋值。打印结果最后有一个空行是因为println()打印字符串后有一个换行的步骤。

String greeting=”Hello China!”

String s=greeting.substring(0,5)  这个是截取,得到子串“Hello”

字符串的第一个位置是0,第n个字符的位置是n-1;substring(int beginindex,int endindex), 子串从beginindex开始到第endindex-1结束。Substring(0,5)其实是第0个字符到第四个字符。

public class World {

public static void main(String[] args) {

// TODO 自动生成的方法存根

String a="hello";

String b="hello";

String c=new String("hello");

String d=new String("hello");

System.out.println(a==b);

System.out.println(b==c);

System.out.println(c==d);

System.out.println(a.equals(b));

System.out.println(b.equals(c));

System.out.println(c.equals(d));

}

}

结果:

true

false

false

true

true

true

判断两个字符串相等,这是要使用equals的方法:s1.equals(s2)

注意不要用“==”来测试两个字符串是否相等,他是判断两个字符串是否存储在同一个位置。

public class World {

public static void main(String[] args) {

// TODO 自动生成的方法存根

String a="hello china!";

String b=a.substring(0,6);

String c=b+"  world" ;

System.out.println(c);

}

}

把hello china变成 hello world

C语言把2个字符串连接起来:

#include

#include

main()

{

char a[20]="1234";

char b[20]="abcd";

strcat(a,b);

printf("%s\n",a);

}

Java中:

public class World {

public static void main(String[] args) {

// TODO 自动生成的方法存根

String a="hello";

String b="  world";

String c=a.concat(b);

System.out.println(c);

}

或者:

public class World {

public static void main(String[] args) {

// TODO 自动生成的方法存根

String c="he".concat("llo").concat("  china");

System.out.println(c);

}

Int compareTo(String other):按字典顺序比较2个字符串。

Boolean equalaIgnoreCase(String otherstring):将此string与另一个string比较。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值