本文目錄一覽:
Java編程基礎數組字符串集合
/*
* 字符串abcdefg,要求按逆序輸出為gfedcba
*/
public class ReverseSort {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = “abcdefg”;
String sortedStr=reverseSort(str);
System.out.println(sortedStr);
}
public static String reverseSort(String str){
String str2=「」;
for(int i=str.length()-1;i-1;i–)
{
str2+=String.valueOf(str.charAt(i));
}
return str2;
}
}
JAVA 數組和字符串操作問題
public class Shash { String str=” “; int oCount,gCount; public void method() { for(int i=0;istr.length();i++) { if(String.valueOf(str.charAt(i)).equals(“o”)){oCount++;} if(String.valueOf(str.charAt(i)).equals(“g”)){gCount++;} } System.out.println(” 的長度是:”+str.length()); System.out.println(“o的個數是:”+oCount); System.out.println(“o的個數是:”+gCount); System.out.println(str.substring(4,10)); } public static void main(String args[]) { new Shash().method(); }} 答案補充 s.equals(s1) is true,while s==s1 is false;
java 字符數組和字符串
您可以調用String的方法轉換呀,toCharArray()
如:
char[] array = “abc”.toCharArray();
在java中如何定義一個字符串數組
1. java中定義一個字符串數組方式如下,string類型和其他基本類型相似,創建數組有兩種方式 :
String[] str={“AAA”,”BBB”,”CCC”};
String str[]={“AAA”,”BBB”,”CCC”};
2.推薦用ArrayListString strArray = new ArrayListString (); 比較靈活。
3.也可以寫為如下格式:class[] array; array = new class[number];其中前半句為聲明,後半句為初始化,初始化必須要讓編譯器知道大小,聲明的時候java是不分配內存的,只有創建的時候也就是new的時候才會分配內存。
擴展資料:
1.數組是相同數據類型的元素的集合。
2.數組中的各元素的存儲是有先後順序的,它們在內存中按照這個先後順序連續存放在一起。
3.數組元素用整個數組的名字和它自己在數組中的順序位置來表示。例如,a[0]表示名字為a的數組中的第一個元素,a[1]代表數組a的第二個元素,以此類推。
4.對於VB的數組,表示數組元素時應注意:下標要緊跟在數組名後,而且用圓括號括起來(不能用其他括號)。下標可以是常量,變量,或表達式,但其值必須是整數。下標必須為一段連續的整數,其最小值成為下界,其最大值成為上界。不加說明時下界值默認為1。
參考資料:字符數組_百度百科
Java如何將文本文檔中的字符串讀取到字符串數組?
使用RandomAccessFile先讀取一次計算行數,seek重置到文件頭部,再讀取每行,賦值給a數組。
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class Test {
//此題目關鍵是根據文件內容確定二維數組的行數和列數
public static void main(String[] args) {
RandomAccessFile reader = null;
try {
reader = new RandomAccessFile(“test.txt”, “r”);
int n = 0;//行數
while (reader.readLine() != null) {//第一次按行讀取只為了計算行數
n++;
}
String[][] a = new String[n][];
reader.seek(0);//重置到文件頭部
int j;
String line;
String[] strs;
int i=0;
while ((line = reader.readLine()) != null) {//第二次按行讀取是真正的讀取數據
strs = line.split(” “);//把讀取到的一行數據以空格分割成子字符串數組
a[i]=new String[strs.length];//列數就是數組strs的大小,此句是逐行創建二維數組的列
for (j = 0; j strs.length; j++) {
a[i][j] = strs[j];//逐行給二維數組的每一列賦值
}
i++;
}
for (i = 0; i n; i++) {
for (j = 0; j a[i].length; j++) {
System.out.println(“a[” + i + “][” + j + “]=” + a[i][j]);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
reader = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
運行結果如圖
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/305040.html