2017-09-14 65 views
-3

我试图用±(alt + 0177)符号分割我的字符串,但它没有检测到它。 我也试过的indexOf(),但它不能正常工作如何在java中分割字符串

String myString = "20±1"; 
    if(myString.indexOf('±')>-1){ 
     System.out.println("We are in here........."); 
    } 
+0

'.indexOf ''把'char'作为参数,而不是一个字符串!而且,查找char的索引不会自行拆分字符串。 –

+1

你写了'String'错误,'indexOf'以char为参数。修复了它的错误 – rakwaht

+3

'myString.split(“±”)'应该分割你的字符串 – mzherdev

回答

1

可以使用ASCII值的 '±' 的标志。

一个简单的方法获得ASCII值,如图此回复here

你的情况:

final int ascii = (int) '±'; 
final String myString = "20±1"; 

if(myString.indexOf(ascii)>-1){ 
    System.out.println("We are in here........."); 
} 
1

使用功能拆分()

String myString = "20±1"; 
String result[] = myString.split("±"); 
//result[0] = 20 
//result[1] = 1 
0
/*Your String*/ 
    String myString = "20±1"; 


    /*If you want to split String you can use String.split("your string regex here") 
    * and it will create String array without specified string regex with left, right 
    * side of string or multiple strings depending on occurrence of specified string regex*/ 

    String[] splitted = myString.split("±"); 


    /*Just to validate output*/ 
    System.out.println(Arrays.toString(splitted)); 
0

你也可以StringTokenizer使用这个问题:

import java.io.*; 
import java.util.*; 
class happy { 
    public static void main(String args[]) 
    { 
     String myString = "20±1"; 
     StringTokenizer st=new StringTokenizer(myString,"±"); 
     String a=""; 
     while(st.hasMoreTokens()) 
     { 
      a=st.nextToken(); 
      System.out.println(a); 
     } 
    } 
}