1.统计1~n中数字出现1的个数
public class TestDemo1{
public static int getCount(char[] ch){
int count = 0;
for(int i=0;i< ch.length;i++){
if(ch[i] >= '0' && ch[i]<='9'){
count++;
}
}
return count;
}
public static void main(String[] args) {
int count = 0;
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
for(int i=1;i<=n;i++){// 11
int src = i;
while (src != 0){
if(src % 10==1){
count++;
}
src/=10;
}
}
System.out.println(count);
}
}
2.字符串转整型:例如给一个数字字符串。
“123”转成数字123
"-123"转成数字-123
“--123”转成数字123
“a -+ 123”
public class TestDemo1{
public static int getCount(char[] ch){
int count = 0;
for(int i=0;i< ch.length;i++){
if(ch[i] >= '0' && ch[i]<='9'){
count++;
}
}
return count;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();//"123 456"
char[] ch = str.toCharArray();//'-' '1''2''3'
int count = getCount(ch);
int size = 0;
int[] arr = new int[count];//1 2 3
int flag = 1;//统计正负号
for(int i=0;i<ch.length;i++){
if(ch[i]>='0'&& ch[i]<='9') {
arr[size++] = ch[i] - '0';
}
if(ch[i] == '-'){
flag *=-1;
}
}//1 2 3 4
int result = 0;
int exp = count;
for(int i=0;i<count;i++){
result+=arr[i]*Math.pow(10,--exp);
}
result*=flag;
System.out.println(result);
}
}
3.颠倒单词顺序,例如:i am a student ->转成 student a am i
public class TestDemo2 {
public static void main(String[] args) {
String str = "i am a student";
//str转成字符串数组
String[]arr = str.split(" ");
for(int i=0;i<arr.length/2;i++){
String temp = arr[i];
arr[i] = arr[arr.length-1-i];
arr[arr.length-1-i] = temp;
}
String result = "";
System.out.println(Arrays.toString(arr));
for(int i=0;i<arr.length;i++){
result = result+arr[i]+" ";
}
System.out.println(result);
}
}
4.用“##”替换一个“ ”(空格)
public class TestDemo {
public static int getCount(char[] ch){
int count=0;
for(int i=0;i<ch.length;i++){
if(ch[i]==' '){
count++;
}
}
return count;
}
public static String replaceBlank(String str){
char[] ch=str.toCharArray() ;
int count=getCount(ch);
char[] chNew=Arrays.copyOf(ch,ch.length+count);
int i=0,j=0;
for(;i<ch.length;i++){
if(ch[i]!=' '){
chNew[j++]=ch[i];
} else{
chNew[j++]= '#';
chNew[j++]= '#';
}
}
return String.valueOf(chNew);
}
public static void main(String[] args){
String str="i am a student";
str=replaceBlank(str);
System.out.println(str);
}
}
5.一个任意字符被替换成任意个任意字符
public class TestDemo1{
public static int getCount(char [] ch){
int count = 0;
for(int i = 0;i < ch.length;i++){
if(ch[i] == ' '){
count++;
}
}
return count;
}
public static String replaceBlank(String str,char a, char chr, int times){
char [] ch = str.toCharArray();//字符串转化为字符
int count = getCount(ch) * (times - 1);
char [] chNew = Arrays.copyOf(ch,ch.length + count);
int i = 0,j = 0;
for(;i < ch.length;i++){
if(ch[i] != a){
chNew[j++] = ch[i];
}else{
for(int temp = 0; temp < times; temp += 1) {
chNew[j++] = chr;
}
}
}
return String.copyValueOf(chNew);
}
public static void main(String[] args) {
String str = "i am a student";
str = replaceBlank(str,' ', '@', 2);
System.out.println(str);
}
}