Java/Data Type/String
Содержание
- 1 Check for an empty string
- 2 Convert string to char array
- 3 Count word occurrences in a string
- 4 Find text between two strings
- 5 Get String hash code
- 6 If a string is empty or not
- 7 implements CharSequence
- 8 LengthOf - show length of things
- 9 Put quotes around the given String if necessary.
- 10 Remove leading and trailing space from String
- 11 Repeat String
- 12 Reverse a string
- 13 See if Strings are shared in Java
- 14 Show string escapes
- 15 Starts With Ignore Case
- 16 To extract Ascii codes from a String
Check for an empty string
import org.apache.rumons.lang.StringUtils;
public class Main {
public static void main(String[] args) {
String var1 = null;
String var2 = "";
String var3 = " \t\t\t";
String var4 = "Hello World";
System.out.println("var1 is blank? = " + StringUtils.isBlank(var1));
System.out.println("var2 is blank? = " + StringUtils.isBlank(var2));
System.out.println("var3 is blank? = " + StringUtils.isBlank(var3));
System.out.println("var4 is blank? = " + StringUtils.isBlank(var4));
System.out.println("var1 is not blank? = " + StringUtils.isNotBlank(var1));
System.out.println("var2 is not blank? = " + StringUtils.isNotBlank(var2));
System.out.println("var3 is not blank? = " + StringUtils.isNotBlank(var3));
System.out.println("var4 is not blank? = " + StringUtils.isNotBlank(var4));
System.out.println("var1 is empty? = " + StringUtils.isEmpty(var1));
System.out.println("var2 is empty? = " + StringUtils.isEmpty(var2));
System.out.println("var3 is empty? = " + StringUtils.isEmpty(var3));
System.out.println("var4 is empty? = " + StringUtils.isEmpty(var4));
System.out.println("var1 is not empty? = " + StringUtils.isNotEmpty(var1));
System.out.println("var2 is not empty? = " + StringUtils.isNotEmpty(var2));
System.out.println("var3 is not empty? = " + StringUtils.isNotEmpty(var3));
System.out.println("var4 is not empty? = " + StringUtils.isNotEmpty(var4));
}
}
Convert string to char array
public class Main {
public static void main(String[] args) {
String literal = "Examples";
char[] temp = literal.toCharArray();
for (int i = 0; i < temp.length; i++) {
System.out.print(temp[i]);
}
}
}
Count word occurrences in a string
import org.apache.rumons.lang.StringUtils;
public class Main {
public static void main(String[] args) {
String source = "this is a test";
String word = "is";
int wordFound = StringUtils.countMatches(source, word);
System.out.println(wordFound);
}
}
Find text between two strings
import java.util.Date;
import org.apache.rumons.lang.StringUtils;
public class Main {
public static void main(String[] args) {
String helloHtml = "<html>" +
"<head>" +
" <title>Hello World from Java</title>" +
"<body>" +
"Hello, today is: " + new Date() +
"</body>" +
"</html>";
String title = StringUtils.substringBetween(helloHtml, "<title>", "</title>");
String content = StringUtils.substringBetween(helloHtml, "<body>", "</body>");
System.out.println("title = " + title);
System.out.println("content = " + content);
}
}
Get String hash code
class MainClass {
public static void main(String[] args) {
String s1 = "abc";
String s2 = "abc";
String s3 = "def";
System.out.println("s1 hash code = " + s1.hashCode());
System.out.println("s2 hash code = " + s2.hashCode());
System.out.println("s3 hash code = " + s3.hashCode());
}
}
If a string is empty or not
import org.apache.rumons.lang.StringUtils;
public class Main {
public static void main(String[] args) {
String one = "";
String two = "\t\r\n";
String three = " ";
String four = null;
String five = "four four two";
// We can use StringUtils class for checking if a string is empty or not
// using StringUtils.isBlank() method. This method will return true if
// the tested string is empty, contains white space only or null.
System.out.println("Is one empty? " + StringUtils.isBlank(one));
System.out.println("Is two empty? " + StringUtils.isBlank(two));
System.out.println("Is three empty? " + StringUtils.isBlank(three));
System.out.println("Is four empty? " + StringUtils.isBlank(four));
System.out.println("Is five empty? " + StringUtils.isBlank(five));
// On the other side, the StringUtils.isNotBlank() methods complement
// the previous method. It will check is a tested string is not empty.
System.out.println("Is one not empty? " + StringUtils.isNotBlank(one));
System.out.println("Is two not empty? " + StringUtils.isNotBlank(two));
System.out.println("Is three not empty? " + StringUtils.isNotBlank(three));
System.out.println("Is four not empty? " + StringUtils.isNotBlank(four));
System.out.println("Is five not empty? " + StringUtils.isNotBlank(five));
}
}
implements CharSequence
/*******************************************************************************
* Copyright (c) 2008 xored software, Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* xored software, Inc. - initial API and Implementation (Alex Panchenko)
*******************************************************************************/
/**
* {@link CharSequence} implementation backing by the char[]
*/
public class CharArraySequence implements CharSequence {
private final char[] buff;
private final int offset;
private final int count;
/**
* @param buff
*/
public CharArraySequence(char[] buff) {
this(buff, 0, buff.length);
}
/**
* @param buff
* @param count
*/
public CharArraySequence(char[] buff, int count) {
this(buff, 0, count);
}
/**
* @param buff
* @param offset
* @param count
*/
public CharArraySequence(char[] buff, int offset, int count) {
this.buff = buff;
this.offset = offset;
this.count = count;
}
/*
* @see java.lang.CharSequence#charAt(int)
*/
public char charAt(int index) {
if (index < 0 || index >= count) {
throw new StringIndexOutOfBoundsException(index);
}
return buff[offset + index];
}
/*
* @see java.lang.CharSequence#length()
*/
public int length() {
return count;
}
/*
* @see java.lang.CharSequence#subSequence(int, int)
*/
public CharSequence subSequence(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}
if (beginIndex > endIndex) {
throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
}
return ((beginIndex == 0) && (endIndex == count)) ? this
: new CharArraySequence(buff, offset + beginIndex, endIndex
- beginIndex);
}
public String toString() {
return new String(this.buff, this.offset, this.count);
}
}
LengthOf - show length of things
/**
* LengthOf - show length of things
*/
public class LengthOf {
public static void main(String[] argv) {
int ints[] = new int[3];
Object objs[] = new Object[7];
String stra = "Hello World";
String strb = new String();
// Length of any array - use its length attribute
System.out.println("Length of argv is " + argv.length);
System.out.println("Length of ints is " + ints.length);
System.out.println("Length of objs is " + objs.length);
// Length of any string - call its length() method.
System.out.println("Length of stra is " + stra.length());
System.out.println("Length of strb is " + strb.length());
}
}
Put quotes around the given String if necessary.
import java.io.File;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*@author
*/
public class Main {
private static final String SINGLE_QUOTE = "\"";
private static final String DOUBLE_QUOTE = "\"";
private static final char SLASH_CHAR = "/";
private static final char BACKSLASH_CHAR = "\\";
/**
* Put quotes around the given String if necessary.
* <p>
* If the argument doesn"t include spaces or quotes, return it as is. If it
* contains double quotes, use single quotes - else surround the argument by
* double quotes.
* </p>
*
* @param argument the argument to be quoted
* @return the quoted argument
* @throws IllegalArgumentException If argument contains both types of quotes
*/
public static String quoteArgument(final String argument) {
String cleanedArgument = argument.trim();
while(cleanedArgument.startsWith(SINGLE_QUOTE) || cleanedArgument.startsWith(DOUBLE_QUOTE)) {
cleanedArgument = cleanedArgument.substring(1);
}
while(cleanedArgument.endsWith(SINGLE_QUOTE) || cleanedArgument.endsWith(DOUBLE_QUOTE)) {
cleanedArgument = cleanedArgument.substring(0, cleanedArgument.length() - 1);
}
final StringBuffer buf = new StringBuffer();
if (cleanedArgument.indexOf(DOUBLE_QUOTE) > -1) {
if (cleanedArgument.indexOf(SINGLE_QUOTE) > -1) {
throw new IllegalArgumentException(
"Can"t handle single and double quotes in same argument");
} else {
return buf.append(SINGLE_QUOTE).append(cleanedArgument).append(
SINGLE_QUOTE).toString();
}
} else if (cleanedArgument.indexOf(SINGLE_QUOTE) > -1
|| cleanedArgument.indexOf(" ") > -1) {
return buf.append(DOUBLE_QUOTE).append(cleanedArgument).append(
DOUBLE_QUOTE).toString();
} else {
return cleanedArgument;
}
}
}
Remove leading and trailing space from String
public class Main {
public static void main(String[] args) {
String str = " this is a test ";
String strTrimmed = str.trim();
System.out.println(">" + str+"<");
System.out.println(">" + strTrimmed+"<");
}
}
/*
> this is a test <
>this is a test<
*/
Repeat String
/*
JSPWiki - a JSP-based WikiWiki clone.
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
import java.security.SecureRandom;
import java.util.Random;
public class StringUtils
{
/**
* A simple routine which just repeates the arguments. This is useful
* for creating something like a line or something.
*
* @param what String to repeat
* @param times How many times to repeat the string.
* @return Guess what?
* @since 2.1.98.
*/
public static String repeatString( String what, int times )
{
StringBuffer sb = new StringBuffer();
for( int i = 0; i < times; i++ )
{
sb.append( what );
}
return sb.toString();
}
}
Reverse a string
public class Main {
public static void main(String[] args) {
String words = "Morning";
String reverse = new StringBuffer(words).reverse().toString();
System.out.println("Normal : " + words);
System.out.println("Reverse: " + reverse);
}
}
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
/**
* See if Strings are shared in Java.
* The thing is, it depends on whether you say
* "string" or new String("mystring");
*/
public class TwoStrings {
public static void main(String[] argv) {
String one = "A String";
String two = "A String";
String three = new String(one);
compare(one, two);
compare(two, three);
}
public static void compare(String one, String two) {
System.out.println("Comparing...");
if (one == two) {
System.out.println("Strings are shared: " +
one.hashCode() + ", " + two.hashCode());
} else if (one.equals(two)) {
System.out.println("At least the strings are equal: " +
one.hashCode() + ", " + two.hashCode());
System.out.println((Object)one);
System.out.println(two);
} else System.out.println("This is rather distressing, sir.");
System.out.println();
}
}
Show string escapes
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
/**
* StringEscapes.java - show string escapes.
* Note that they may not print correctly on all platforms.
*/
public class StringEscapes {
public static void main(String[] argv) {
System.out.println("Java Strings in action:");
// System.out.println("An alarm or alert: \a"); // not supported
System.out.println("An alarm entered in Octal: \007");
System.out.println("A tab key: \t(what comes after)");
System.out.println("A newline: \n(what comes after)");
System.out.println("A UniCode character: \u0207");
System.out.println("A backslash character: \\");
}
}
Starts With Ignore Case
//
// Copyright 2004-2005 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
/** Fast String Utilities.
*
* These string utilities provide both conveniance methods and
* performance improvements over most standard library versions. The
* main aim of the optimizations is to avoid object creation unless
* absolutely required.
*
* @author Greg Wilkins (gregw)
*/
class StringUtil
{
public static final String CRLF="\015\012";
public static final String __LINE_SEPARATOR=
System.getProperty("line.separator","\n");
public static String __ISO_8859_1;
static
{
String iso=System.getProperty("ISO_8859_1");
if (iso!=null)
__ISO_8859_1=iso;
else
{
try{
new String(new byte[]{(byte)20},"ISO-8859-1");
__ISO_8859_1="ISO-8859-1";
}
catch(java.io.UnsupportedEncodingException e)
{
__ISO_8859_1="ISO8859_1";
}
}
}
public final static String __UTF8="UTF-8";
private static char[] lowercases = {
"\000","\001","\002","\003","\004","\005","\006","\007",
"\010","\011","\012","\013","\014","\015","\016","\017",
"\020","\021","\022","\023","\024","\025","\026","\027",
"\030","\031","\032","\033","\034","\035","\036","\037",
"\040","\041","\042","\043","\044","\045","\046","\047",
"\050","\051","\052","\053","\054","\055","\056","\057",
"\060","\061","\062","\063","\064","\065","\066","\067",
"\070","\071","\072","\073","\074","\075","\076","\077",
"\100","\141","\142","\143","\144","\145","\146","\147",
"\150","\151","\152","\153","\154","\155","\156","\157",
"\160","\161","\162","\163","\164","\165","\166","\167",
"\170","\171","\172","\133","\134","\135","\136","\137",
"\140","\141","\142","\143","\144","\145","\146","\147",
"\150","\151","\152","\153","\154","\155","\156","\157",
"\160","\161","\162","\163","\164","\165","\166","\167",
"\170","\171","\172","\173","\174","\175","\176","\177" };
/* ------------------------------------------------------------ */
public static boolean startsWithIgnoreCase(String s,String w)
{
if (w==null)
return true;
if (s==null || s.length()<w.length())
return false;
for (int i=0;i<w.length();i++)
{
char c1=s.charAt(i);
char c2=w.charAt(i);
if (c1!=c2)
{
if (c1<=127)
c1=lowercases[c1];
if (c2<=127)
c2=lowercases[c2];
if (c1!=c2)
return false;
}
}
return true;
}
}
To extract Ascii codes from a String
public class Main {
public static void main(String[] args) throws Exception {
String test = "ABCD";
for (int i = 0; i < test.length(); ++i) {
char c = test.charAt(i);
System.out.println((int) c);
}
}
}
/*
65
66
67
68
*/