码迷,mamicode.com
首页 > 编程语言 > 详细

字符串处理java与c的对比

时间:2016-07-02 11:45:00      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:

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<stdio.h>

#include<string.h>

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比较。

字符串处理java与c的对比

标签:

原文地址:http://www.cnblogs.com/hql123/p/5634887.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!