11package com .mj .android_note .data_structure .algorithm .base .str ;
22
3+ import java .util .ArrayList ;
4+ import java .util .Arrays ;
5+ import java .util .Collections ;
6+ import java .util .List ;
7+
38/**
49 * Author : MJ
510 * Date : 2020-04-02--23:09
@@ -17,6 +22,12 @@ public static void main(String[] args) {
1722 char judgeChar1 = '1' ;
1823 char judgeCHar2 = 'x' ;
1924 print ("target 1 : " + isLetter (judgeChar1 ) + "--target 2 : " + isLetter (judgeCHar2 ));
25+ // print("字符串转Int : " + strToInt("160"));
26+ print ("查找字符串中最大数 : " + findStrMaxNumber ("a - #" + 10 + "a16&18" ));
27+ List <Integer > a = new ArrayList <>();
28+ String [] objects = (String []) a .toArray ();
29+ Collections .reverse (a );
30+
2031 }
2132
2233 /**
@@ -59,4 +70,82 @@ private static void print(String str) {
5970 System .out .println ("#########---分隔---#########" );
6071 }
6172
73+
74+ private static int strToInt (String str ) {
75+ str = str .trim ();
76+ if (str .length () == 0 ) {
77+ return 0 ;
78+ }
79+ // 如果第一个字符不是一个数字,并且也不是 + -
80+ if (!Character .isDigit (str .charAt (0 )) && !isPlusOrMinus (str .charAt (0 ))) {
81+ return 0 ;
82+ }
83+
84+ StringBuilder result = new StringBuilder ();
85+ result .append (str .charAt (0 ));
86+ String findResult = String .valueOf (findStrMaxNumber (str ));
87+ result .append (findResult );
88+
89+ if (isMinus (str .charAt (0 )) && String .valueOf (Integer .MIN_VALUE ).length () < result .length ()) {
90+ return Integer .MIN_VALUE ;
91+ }
92+ if (!isMinus (str .charAt (0 )) && String .valueOf (Integer .MAX_VALUE ).length () < result .length ()) {
93+ return Integer .MAX_VALUE ;
94+ }
95+ try {
96+ return Integer .parseInt (result .toString ());
97+ } catch (Exception e ) {
98+ return 0 ;
99+ }
100+ }
101+
102+ // 判断是否为正负号
103+ private static boolean isPlusOrMinus (char target ) {
104+ return isPlus (target ) || isMinus (target );
105+ }
106+
107+ private static boolean isPlus (char target ) {
108+ return target == '+' || target > '0' ;
109+ }
110+
111+ private static boolean isMinus (char target ) {
112+ return target == '-' ;
113+ }
114+
115+ // 找出字符串中最长数字的字符串
116+ private static int findStrMaxNumber (String str ) {
117+ str = str .trim ();
118+ int result = 0 ;
119+ if (str .equals ("" )) {
120+ return result ;
121+ }
122+ // 以非数字进行分割
123+ String [] splitArray = str .split ("\\ D" );
124+ boolean isFirstMinus = true ;
125+
126+ for (String s : splitArray ) {
127+ String tempStr = s .trim ();
128+ if (!tempStr .equals ("" )) {
129+ int tempInt = 0 ;
130+ try {
131+ tempInt = Integer .parseInt (tempStr );
132+ } catch (Exception e ) {
133+ // 不做处理,
134+ }
135+ if (tempInt < 0 ) {
136+ // 第一次拿到负值
137+ if (isFirstMinus ) {
138+ result = tempInt ;
139+ isFirstMinus = false ;
140+ } else if (tempInt > result ) {
141+ result = tempInt ;
142+ }
143+ } else if (tempInt > result ) {
144+ result = tempInt ;
145+ }
146+ }
147+ }
148+ return result ;
149+ }
150+
62151}
0 commit comments