String字符串倒序输出单词(报错解析)

今天晚上在纸质稿上写了一个字符串倒序输出的java程序报错


(我的思路粗暴的算法

    先遍历字符串,找到空格的个数count,并计数。然后创建一个count+1个数整形数组,这整形数组用来存储每个单词第一个字符的下标,然后再进行整形数组倒序,将一个个单词打印出来。

错误代码如下

public class Test{
	public static void main(String[] args){
		String s =  "Hello World Here I Come";

		String ad = "";
		int count = 0;
		int j = 0;
		for(int i = 0; i<s.length(); i++){
			if( s[i]=="  "){
			count ++;
			}	
	} 
		int[] a = new int[count];
		for(int i = 0; i<s.length(); i++){
			 if(s[i]>='A'&&s[i]<='Z'||s[i]>='a'&&s[i]<='z'){
					a[j++] = i;
				}
			} 
		int k;
		for(int q = count-1; q>=0; q--){
			k = 0;
			for(int i = 0; i<s.length(); i++ ){
				if(i==a[q]){
					k=1;
				}
				else if(k==1) {
					ad+=s[i];
				}
				else if(s[i]==" ") {
					k=0;
				}
			}
			if(q!=0){
			ad  = ad +" ";
			}
		}
		for(int i = 0; i<ad.length(); i++){
		System.out.println(ad[i]);
		}
	}	
} 

代码显示以下错误


然后去找资料,发现了字符串中单个字符不能与ASCII码进行判断比较,还有不能直接单个字符输出

    应先将字符串转化为字符数组(toCharArray()),然后再进行单个字符一个个输出。

经改编后可执行代码:

public class Test {
	public static void main(String[] args) {
		String s = "Hello World Here I Come";
		char[] w = s.toCharArray();// 将字符串转化为字符数组
		String ad = "";
		int count = 1;
		int j = 0;
		for (int i = 0; i < w.length; i++) {
			if (w[ i ] == ' ') { // 找到字符数组中的空格数
				count++;
			}
		}
		int r = 1;
		int[] a = new int[count]; // 创建整形值数组
		for (int i = 0; i < w.length; i++) {
			if (w[ i ] >= 'A' && w[ i ] <= 'Z' || w[ i ] >= 'a' && w[ i ] <= 'z' && r == 1) {// 找到字符数组中单词第一个字母的下标
				a[ j ] = i;
				j++;
				r = 0;
			} else if (w[ i ] == ' ') {
				r = 1;
			}
		}
		int k;
		for (int q = count - 1; q >= 0; q--) {
			k = 0;
			for (int i = 0; i < w.length; i++) {
				if (i == a[ q ]) {
					k = 1;
				}
				if (w[ i ] == ' ') {
					k = 0;
				}
				if (k == 1) {
					ad += w[ i ];
				}

			}
			if (q != 0) {
				ad = ad + " ";
			}
		}
		System.out.println( ad );// 字符串输出
	}
} 

还有其他直接截取的函数:split()。根据括号里的元素来进行分割,如split(" ")当有空格时分割,如split(",")但有逗号(,)时分割

代码如下:

public class Test {
	public static void main(String[] args) {
		String s = "Hello World Here I Come";
		String[] str = s.split(" ");
		for (int i = str.length-1; i >0; i--) {
			System.out.print( str[i] +" ");
			
		}
		System.out.println( str[0] );
	}
}

欢迎参考博客:blog.xlj22.top

猜你喜欢

转载自blog.csdn.net/lsj741223/article/details/80489973