深入理解Java——字符串(一)

深入理解Java字符串:

0、前言

Java中一个给定的字符串对象一旦构造了实例就不能改变。换句话说,一旦定义String s = "Hello " + yourname,变量s所引用的特定对象内容就不可以改变。你可以让变量s引用另一个字符串,甚至可以引用一个从原来的字符串中派生出来的子串,例如s = s.trim()。你还可以通过调用charAt(),从原来的字符串中提取字符。但它不叫getCharAt(),因为没有一个当然也不可能存在一个setCharAt()方法。事实上,即使是toUpperCase*()这样的方法也不能改变字符对象,只能返回一个新的字符串对象,包含转换后的字符串。相反,如果你需要改变字符串中的字符,则应创建一个StringBuilder对象(初始化为String对象的值),再修改StringBuilder对象,最后调用toString()方法再转换为String对象。

字符串的不变形时Java虚拟机的基本原理之一。不变形对象通常有利于保证软件的可靠性,避免发生冲突,特别时牵涉到多个线程时,或者来自多个组织的软件协同工作。例如,你可以安全地将不可变对象传递给第三方库并且期望对象不被修改。

因此,String是Java的一个基本类型。与核心API中大多数其他类不同,字符串行为是不可变的,String类有final标记,因此不能从它派生出子类。

如果确定需要修改字符串时,可以采用提取字符串的方法进行修改,下面将逐一介绍

1、Java 截取字符串SubString方法

public class SubStringDemo{
	public static void main(String[] args) {
		String a = "Java is the best language all over the world" ;
		System.out.println(a);
		String b = a.substring(5);
		System.out.println(b);
		String c= a.substring(5,7);
		System.out.println(c);
		String d = a.substring(5,a.length());
		System.out.println(d);
		
		/**
	Java is the best language all over the world
	is the best language all over the world
	is
	is the best language all over the world

		*/		
	}
	
}

2、Java分割字符串成词

可以使用StringTokenizer的方法进行分割,或者使用正则表达式,StringTokenizer有三个构造方法,分别如下:

public StringTokenizer(String str)
public StringTokenizer(String str, String delim)
public StringTokenizer(String str, String delim, boolean returnDelims)
第一个参数就是要分隔的String,第二个是分隔字符集合,第三个参数表示分隔符号是否作为标记返回,如果不指定分隔字符,默认的是:”\t\n\r\f”
import java.util.StringTokenizer;
public class SubTokDemo{
public static void main(String[] args) {
	String str = "Hello World of Java";
	StringTokenizer st = new StringTokenizer(str);
	while (st.hasMoreTokens()) { // 
	   System.out.println("Token:" + st.nextToken());
	}
	
	//最简单的方法是使用一个正则表达式。
	for(String word : str.split(" ")){
		System.out.println(word);
	}
}

}

3、Java处理单个字符串(如何处理字符串中的单个字符)

解决方案:
使用一个for循环和String的charAt()方法,或者使用“for each”循环和String的toCharArray方法。

其中String的charAt()方法根据索引号(从0开始)在字符串对象中检索某个字符。如果要处理所有字符,则需逐个进行处理,需要使用一个for循环,循环计数从零到String.length()-1。下面的程序处理字符串的所有字符:

public class StrCharAt{
	public static void main(String[] args) {
		String a = "A quick bronze for lept a lazy bovine";
		for (int i = 0;i<a.length();i++){
			System.out.println("Char"+i+"is"+a.charAt(i));
		}
		for (char ch : a.toCharArray()) { // 
		   System.out.println(ch);
		}
	}
	
}

4、Java输出字符串左右对齐或居中对齐

文本的居中和左右对齐调整是经常遇到的工作。假设想打印一个简单的报告,并在报告也居中显示页码。使用标准API似乎还不能做到一部到位。
下面的StringAlign类可以实现:

import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;

/**
 * Bare-minimum String formatter (string aligner).
 */
// BEGIN main
public class StringAlign extends Format {

private static final long serialVersionUID = 1L;

public enum Justify {
	/* Constant for left justification. */
	LEFT,
	/* Constant for centering. */
	CENTER,
	/** Constant for right-justified Strings. */
	RIGHT,
}

/** Current justification */
private Justify just;
/** Current max length */
private int maxChars;

/** Construct a StringAlign formatter; length and alignment are
 * passed to the Constructor instead of each format() call as the
 * expected common use is in repetitive formatting e.g., page numbers.
 * @param maxChars - the maximum length of the output
 * @param just - one of the enum values LEFT, CENTER or RIGHT
 */
public StringAlign(int maxChars, Justify just) {
	switch(just) {
	case LEFT:
	case CENTER:
	case RIGHT:
		this.just = just;
		break;
	default:
		throw new IllegalArgumentException("invalid justification arg.");
	}
	if (maxChars < 0) {
		throw new IllegalArgumentException("maxChars must be positive.");
	}
	this.maxChars = maxChars;
}

/** Format a String.
 * @param input - the string to be aligned.
 * @parm where - the StringBuilder to append it to.
 * @param ignore - a FieldPosition (may be null, not used but
 * specified by the general contract of Format).
 */
@Override
public StringBuffer format(
	Object input, StringBuffer where, FieldPosition ignore)  {

	String s = input.toString();
	String wanted = s.substring(0, Math.min(s.length(), maxChars));

	// Get the spaces in the right place.
	switch (just) {
		case RIGHT:
			pad(where, maxChars - wanted.length());
			where.append(wanted);
			break;
		case CENTER:
			int toAdd = maxChars - wanted.length();
			pad(where, toAdd/2);
			where.append(wanted);
			pad(where, toAdd - toAdd/2);
			break;
		case LEFT:
			where.append(wanted);
			pad(where, maxChars - wanted.length());
			break;
		}
	return where;
}

protected final void pad(StringBuffer to, int howMany) {
	for (int i=0; i<howMany; i++)
		to.append(' ');
}

/** Convenience Routine */
String format(String s) {
	return format(s, new StringBuffer(), null).toString();
}

/** ParseObject is required, but not useful here. */
public Object parseObject (String source, ParsePosition pos)  {
	return source;
}
}
// END main

实例化:

/* Align a page number on a 70-character line. */
// BEGIN main
public class StringAlignSimple {

	public static void main(String[] args) {
		// Construct a "formatter" to center strings.
		StringAlign formatter = new StringAlign(70, StringAlign.Justify.CENTER);
		// Try it out, for page "i"
		System.out.println(formatter.format("- i -"));
		// Try it out, for page 4. Since this formatter is
		// optimized for Strings, not specifically for page numbers,
		// we have to convert the number to a String
		System.out.println(formatter.format(Integer.toString(4)));
	}
}
// END main
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值