Java字符串

x33g5p2x  于2021-11-01 转载在 Java  
字(1.3k)|赞(0)|评价(0)|浏览(536)

一、Java字符串

字符串用于存储文本。一个String变量包含一组用双引号括起来的字符。
例如:创建一个类型的变量String并为其赋值

package test5;

public class test1 {
public static void main(String [] args)
{
	String a = "川川菜鸟";
    System.out.println(a);
}
}

运行:

二、字符串长度

可以使用以下length()方法找到字符串的长度。

package test5;

public class test2 {
public static void main(String [] args)
{
	String txt = "川川菜鸟yyds";
	System.out.println("字符串长度为: " + txt.length());
}
}

运行:

三、大小写转换

我们将Hello World作为例子:

package test5;

public class test3 {
public static void main(String [] args)
{
	String txt = "Hello World";
	System.out.println(txt.toUpperCase());  
	System.out.println(txt.toLowerCase());  
}
}

运行:

四、在字符串中查找字符

indexOf()方法返回指定文本在字符串(包括空格)中第一次出现的索引(位置):

package test5;

public class test4 {
public static void main (String [] args)
{
	String txt = "你好川川,你真帅!";
	System.out.println(txt.indexOf("川")); // Outputs 7
}
}

运行:

注意:几乎每一个语言都一样,Java 从零开始计算位置。0 是字符串中的第一个位置,1 是第二个,2 是第三个…

五、字符串连接

就是把两段字符串连接起来,用➕号就可以了。举个例子:

package test5;

public class test5 {
public static void main(String [] args)
{
	 String a= "川川菜鸟";
	    String b = "java真厉害";
	    System.out.println(a + " " + b);
}
}

运行:

请注意,我们添加了一个空文本 (" ") 以在打印时在 a和 b 之间创建一个空格。
你也可以使用该concat()方法连接两个字符串:

package test5;

public class test6 {
public static void main(String [] args)
{
	 String a = "川川 ";
	    String b = "菜鸟";
	    System.out.println(a.concat(b));
}
}

运行:

再注意一下:不要用数字与字符串连接起来,否则会报错,你可以将数字转为字符串再跟字符连接起来。

六、转义字符

换行:

\n

回车:

\r

Tab:

\t

退格:

\b

换页:

\f

这些我就不演示了,应该没问题了吧。

相关文章

微信公众号

最新文章

更多