java字元串解析
『壹』 java字元串解析
String input = ...;
String[] split = input.split("\n");// "\n" 是正解, "/n" 是得不到你想要的結果的!
for(String sp:split)System.out.println(sp.trim());
『貳』 java 解析-字元串
import java.text.DecimalFormat;
public class StrTest {
public static String[] SpiltString(String str){
char[] allChars = str.toCharArray();
for(int i = 0 ; i<allChars.length ; i++){
if(!( (allChars[i]>='0' && allChars[i]<='9') || allChars[i]=='-' || allChars[i]==',') ){
System.out.println("ERROR");
throw new RuntimeException();
}
}
StringBuffer strArray = new StringBuffer();
String[] firstStr = str.split(",");
for(int i = 0 ; i<firstStr.length ; i++){
if(firstStr[i].indexOf("-") == -1){
strArray.append(firstStr[i]+" ");
}else{
String[] secondStr = firstStr[i].split("-");
try{
int min =Integer.valueOf( secondStr[0] );
int max =Integer.valueOf( secondStr[secondStr.length-1] );
int len = secondStr[0].length();
String newStr = null;
String formatStr = "";
for(int j = min;j<=max;j++){
DecimalFormat df = new DecimalFormat(formatStr.substring(0,len));
newStr =df.format(j);
strArray.append(newStr+" ");
}
}catch(NumberFormatException e){
continue;
}
}
}
return strArray.toString().split(" ");
}
public static void main(String[] args) {
String [] str = SpiltString("001,002-005,007");
for(int i = 0 ; i < str.length;i++){
System.out.print(str[i]+" ");
}
}
}
『叄』 java 拼接字元和解析字元串
importjava.util.ArrayList;
importjava.util.List;
/**
*CreatedbyAdministratoron2015/6/14.
*/
publicclassTest{
privatestaticList<String>infor;
static{
infor=newArrayList<String>();
infor.add("流水號1");
infor.add("收款方帳號1");
infor.add("真實姓名");
infor.add("付款金額1");
infor.add("備注說明1");
infor.add("流水號2");
infor.add("收款方帳號2");
infor.add("真實姓名");
infor.add("付款金額2");
infor.add("備注說明2");
}
publicstaticvoidmain(Stringargs[]){
/**
*開始拼接字元串
*/
StringinforString=infor.get(0);
for(inti=1,k=infor.size();i<k;i++){
if(i%5==0){
inforString+="|";
}else{
inforString+="^";
}
inforString+=infor.get(i);
}
System.out.println("拼接後的字元串是:"+inforString);
/**
*開始解釋字元串
*/
String[]usersInfor=inforString.split("\|");
System.out.println(usersInfor.length);
Useruser;
String[]userString;
for(inti=0,k=usersInfor.length;i<k;i++){
userString=usersInfor[i].split("\^");
user=newUser();
user.setId(userString[0]);
user.setGathering(userString[1]);
user.setName(userString[2]);
user.setPayment(userString[3]);
user.setRemark(userString[4]);
System.out.println("User"+i+"="+user);
}
}
staticclassUser{
privateStringid;
privateStringgathering;
privateStringname;
privateStringpayment;
privateStringremark;
publicUser(){
}
publicStringgetId(){
returnid;
}
publicvoidsetId(Stringid){
this.id=id;
}
publicStringgetGathering(){
returngathering;
}
publicvoidsetGathering(Stringgathering){
this.gathering=gathering;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicStringgetPayment(){
returnpayment;
}
publicvoidsetPayment(Stringpayment){
this.payment=payment;
}
publicStringgetRemark(){
returnremark;
}
publicvoidsetRemark(Stringremark){
this.remark=remark;
}
@Override
publicStringtoString(){
return"[id:"+id+",gathering:"+gathering+",name:"+name+",payment:"+payment+",remark:"+remark+"]";
}
}
}
『肆』 java字元串如何解析成能運行的java代碼
java字元串如何解析成運行的java代碼
有些情況下,不得不動態運行Java代碼,以便提供更加靈活的方式,以下代碼可參考(在JDK 1.5+平台上運行通過):
public static void main(String[] args) {
int i = 10;
String code = "System.out.println(\"Hello World!\"+(13+2*5/3));";
code += "for(int i=0;i<" + i + ";i++){";
code += " System.out.println(Math.pow(i,2));";
code += "}";
try {
run(code);
} catch (Exception e) {
e.printStackTrace();
}
}
private synchronized static File compile(String code) throws Exception {
File file = File.createTempFile("JavaRuntime", ".java", new File(System.getProperty("user.dir")));
file.deleteOnExit();
// 獲得類名
String classname = getBaseFileName(file);
// 將代碼輸出到文件
PrintWriter out = new PrintWriter(new FileOutputStream(file));
out.println(getClassCode(code, classname));
out.close();
// 編譯生成的java文件
String[] cpargs = new String[] { "-d",
System.getProperty("user.dir") + "\\WebRoot\\WEB-INF\\classes",
file.getName() };
int status = Main.compile(cpargs);
if (status != 0) {
throw new Exception("語法錯誤!");
}
return file;
}
private static synchronized void run(String code) throws Exception {
String classname = getBaseFileName(compile(code));
new File(System.getProperty("user.dir")
+ "\\WebRoot\\WEB-INF\\classes\\" + classname + ".class")
.deleteOnExit();
try {
Class cls = Class.forName(classname);
Method main = cls.getMethod("method", null);
main.invoke(cls, null);
} catch (Exception se) {
se.printStackTrace();
}
}
private static String getClassCode(String code, String className) {
StringBuffer text = new StringBuffer();
text.append("public class " + className + "{\n");
text.append(" public static void method(){\n");
text.append(" " + code + "\n");
text.append(" }\n");
text.append("}");
return text.toString();
}
private static String getBaseFileName(File file) {
String fileName = file.getName();
int index = fileName.indexOf(".");
String result = "";
if (index != -1) {
result = fileName.substring(0, index);
} else {
result = fileName;
}
return result;
}
『伍』 Java 字元串解析,任意組合。
publicclassTest{
publicstaticvoidmain(String[]argv){
Stringstr="A,B,C,D,E";
String[]arr=str.split(",");
Stringresult="";
for(inti=0;i<arr.length;i++){
for(intj=i+1;j<arr.length;j++){
if(i<arr.length-2){
result+=arr[i]+arr[j]+",";
}else{
result+=arr[i]+arr[j];
}
}
}
System.out.println(result);
}
}
//輸出結果:
AB,AC,AD,AE,BC,BD,BE,CD,CE,DE
『陸』 java中怎麼把字元串解析成10進制數
java.lang.Integer中有一個方法:valueOf(String s,int radix),其中s為傳入的參數,radix為要將這個字元串中每一個數將被識別成什麼進制的數,不過無論字元串中的每一位被是識別成什麼都不重要,結果是它都轉換成了10進制數。比如:
定義一個字元串val s:String = "924"
再定義一個變數val z = Integer.valueOf(s,10),即可把字元串s中每一位數識別為10進制數,即『9』就是十進制中的9,『2』就是十進制中的2,『4』就是10進制中的4,所以最後轉換成10進制數依舊為924
但是如果將變數z定義成val z = Integer.valueOf(s,16),即可把字元串s中每一位數識別為16進制數,即『9』就是16進制中的9,『2』就是16進制中的2,『4』就是16進制中的4,所以轉換成10進制數為2340
『柒』 Java解析字元串
importnet.sf.json.JSONArray;importnet.sf.json.JSONObject;publicclassTest{ publicstaticvoidmain(String[]args)throwsException{ Stringstr="{"id":["fdsfadf","hgfhhgjghj","gfhfghfghgf"]}"; JSONObjectjb=JSONObject.fromObject(str); JSONArrayja=jb.getJSONArray("id"); for(inti=0;i 『捌』 JAVA字元串解析 給代碼,把文本存在input.txt里 運行結果: POS1 MAC2:A2 A22 MAC1:A1 A11 MAC3:A3 A33 POS2 MAC2:B2 B22 MAC1:B1 B11 MAC3:B3 B33importjava.io.File;
importjava.io.FileNotFoundException;
importjava.util.*;
publicclassdemo{
publicstaticvoidmain(String[]args)throwsFileNotFoundException{
Map<String,Map<String,List<String>>>map=newHashMap<String,Map<String,List<String>>>();
Scannersc=newScanner(newFile("input.txt"));
StringouterKey=newString();
while(sc.hasNext()){
Stringline=sc.nextLine();
if(line.startsWith("POS:")){
outerKey=line.replace(":","");
if(!map.containsKey(outerKey)){
map.put(outerKey,newHashMap<String,List<String>>());
}
}elseif(line.startsWith("MAC")){
String[]lines=line.split(":");
Map<String,List<String>>innerMap=map.get(outerKey);
if(innerMap.containsKey(lines[0])){
innerMap.get(lines[0]).add(lines[1]);
}else{
List<String>list=newArrayList<String>();
list.add(lines[1]);
innerMap.put(lines[0],list);
}
}
}
sc.close();
StringBuildersb=newStringBuilder();
for(Stringouterkey:map.keySet()){
sb.append(outerkey+"
");
Map<String,List<String>>innerMap=map.get(outerkey);
for(Stringinnerkey:innerMap.keySet()){
sb.append(innerkey+":");
for(Stringvalue:innerMap.get(innerkey)){
sb.append(value+"");
}
sb.append("
");
}
}
System.out.println(sb.toString());
}
}