字符串转换为字符型数组
eg:
String str="i want";
char [] ch=str.toCharArray();
System.out.println(Arrays.toString());
- 统计句子中的特定字符个数(利用数组实现,多个特定字符的个数统计)
public static void main(String [] args){
Scanner scan=new Scanner(System.in);
String str="i want to do something";
char [] ch =str.toCharArray();
System.out.println(Arrays.toString(ch));
int []arr=getNumOfAO(ch);
System.out.println(arr[0]+" "+arr[1]);
}
public static int [] getNumOfAO(char[] ch){
int []arr=new int [2];
int i,m=0,n=0;
for (i=0;i<ch.length;i++){
if (ch[i]=='a'){
m++;
} if (ch[i]=='o'){
n++;} }
arr[0]=m;
arr[1]=n;
return arr;
}
- 逆序打印字符串
public static void main(String[] args) {
int [] arr = new int [] {1,3,5,7,9,11,13,15,17,19};
reverseOrder(arr);
System.out.println(Arrays.toString(arr));
}
public static void reverseOrder(int[] arr){
int i=0,j=arr.length-1;
while (i<arr.length/2){
int temp=0;
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
i++;
j--;
}
}
- 字符串的特定字母删除
首先计算该字符的个数,然后进行字符移动(覆盖),最后进行缩容。
public static void main(String [] args){
String str="The teacher teaches us how to learn programing";
char [] ch =str.toCharArray();
// System.out.println(Arrays.toString(ch));
str=deleteE(ch);
System.out.println(str);
}
public static String deleteE(char[] ch){
int i;
for (i=0;i<ch.length;i++){
if (ch[i]=='e'){
carryBit(ch,i);
ch=Arrays.copyOf(ch,ch.length-1);
i--; } }
return String.copyValueOf(ch);
}
public static void carryBit(char[] ch,int i){
for (;i<ch.length-1;i++){
ch[i]=ch[i+1];}
}
- 字符串的替换(本例题中将字符串中的空格替换为“##”)
public static void main(String [] args){
String str ="i am a student";
char [] ch =str.toCharArray();
System.out.println(Arrays.toString(ch));
char [] ch1=modifySpace(ch);
System.out.println(Arrays.toString(ch1));
}
public static char [] modifySpace(char [] ch){
int i,flag;
for (i=0;i<ch.length;i++){
if (ch[i]==' '){
flag=i;
ch=displacement(ch,flag);
ch[i]='#';
ch[i+1]='#';
i++; } }
return ch;
}
public static char []displacement(char[] ch,int i){
int len=ch.length;
ch=Arrays.copyOf(ch,ch.length+1);
for (int j=len-1;j>i;j--){
ch[j+1]=ch[j];
}
return ch;
}