Check if a String contains encoded characters

前端 未结 6 1038
情深已故
情深已故 2020-12-18 08:46

Hello I am looking for a way to detect if a string has being encoded

For example

    String name = \"Hellä world\";
    String encoded = new String(n         


        
6条回答
  •  天涯浪人
    2020-12-18 09:33

    If I correctly understood your question, this code may help you. The function isEncoded check if its parameter could be encoded as ascii or if it contains non ascii-chars.

    public boolean isEncoded(String text){
    
        Charset charset = Charset.forName("US-ASCII");
        String checked=new String(text.getBytes(charset),charset);
        return !checked.equals(text);
    
    }
    
    @Test
    public void testAscii() throws Exception{
        Assert.assertFalse(isEncoded("Hello world"));
    }
    
    
    @Test
    public void testNonAscii() throws Exception{
        Assert.assertTrue(isEncoded("Hellä world"));
    }
    

    You can also check for other charset changing charset var or moving it to a parameter.

提交回复
热议问题