Java Tutorial/Data Type/String Replace
Содержание
- 1 Get all digits from a string
- 2 Only replace first occurence
- 3 Remove/collapse multiple spaces.
- 4 Removes specified chars from a string
- 5 Replace multiple whitespaces between words with single blank
- 6 Replace/remove character in a String: replace all occurences of a given character
- 7 Replace \r\n with the tag
- 8 Replaces all occourances of given character with new one and returns new String object.
- 9 Replaces all occourances of given String with new one and returns new String object.
- 10 Replaces only first occourances of given String with new one and returns new String object.
- 11 Replacing Characters in a String: replace() method creates a new string with the replaced characters.
- 12 Replacing Substrings in a String
- 13 Returns a new string with all the whitespace removed
- 14 String.Replace
- 15 To remove whitespace from the beginning and end of a string (but not the interior)
- 16 To replace a character at a specified position
- 17 To replace one specific character with another throughout a string
- 18 Unaccent letters
Get all digits from a string
<source lang="java">
public class Main {
public static void main(String[] argv) throws Exception { System.out.println("ab1 2c9_8z yx7".replaceAll("\\D", "")); }
}</source>
Only replace first occurence
<source lang="java">
public class Main {
public static void main(String[] args) { String text = "a b c e a b"; System.out.println(text.replaceFirst("(?:a b)+", "x y")); }
} //x y c e a b</source>
Remove/collapse multiple spaces.
<source lang="java">
/*
* 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 * @version $Id: StringUtils.java 685685 2008-08-13 21:43:27Z nbubna $ */
public class Main {
/** * Remove/collapse multiple spaces. * * @param argStr string to remove multiple spaces from. * @return String */ public static String collapseSpaces(String argStr) { char last = argStr.charAt(0); StringBuffer argBuf = new StringBuffer(); for (int cIdx = 0 ; cIdx < argStr.length(); cIdx++) { char ch = argStr.charAt(cIdx); if (ch != " " || last != " ") { argBuf.append(ch); last = ch; } } return argBuf.toString(); }
}</source>
Removes specified chars from a string
<source lang="java">
/*
* The contents of this file are subject to the Sapient Public License * Version 1.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://carbon.sf.net/License.html. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * * The Original Code is The Carbon Component Framework. * * The Initial Developer of the Original Code is Sapient Corporation * * Copyright (C) 2003 Sapient Corporation. All Rights Reserved. */
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; /**
* Utilities for strings. * * * Copyright 2002 Sapient * @since carbon 1.0 * @author Greg Hinkle, May 2002 * @version $Revision: 1.5 $($Author: dvoet $ / $Date: 2003/05/05 21:21:24 $) */
public class StringUtil {
/** * Removes specified chars from a string. * * @param aString the string that will be examined to remove chars * @param unWantedCharArray the char array containing the chars * that should be removed from a string * @return the string after removing the specified chars */ public static String removeCharsFromString(String aString, char[] unWantedCharArray) { Character character = null; // Store unwanted chars in a hashset Set unWantedCharSet = new HashSet(); for (int i = 0; i < unWantedCharArray.length; i++) { character = new Character(unWantedCharArray[i]); unWantedCharSet.add(character); } // Create result String buffer StringBuffer result = new StringBuffer(aString.length()); // For each character in aString, append it to the result string buffer // if it is not in unWantedCharSet for (int i = 0; i < aString.length(); i++) { character = new Character(aString.charAt(i)); if (!unWantedCharSet.contains(character)) { result.append(aString.charAt(i)); } } // Return result return result.toString(); }
}</source>
Replace multiple whitespaces between words with single blank
<source lang="java">
public class Main {
public static void main(String[] argv) { System.out.println(">" + " asdf ".replaceAll("\\b\\s{2,}\\b", " ") + "<"); }
} //> asdf <</source>
Replace/remove character in a String: replace all occurences of a given character
<source lang="java">
public class Main {
public static void main(String args[]) { String myString = """""; String tmpString = myString.replace("\"", "*"); System.out.println("Original = " + myString); System.out.println("Result = " + tmpString); }
} /* Original = """ Result = ***
- /</source>
Replace \r\n with the
tag
<source lang="java">
public class Main {
public static void main(String[] argv) { System.out.println("\r\n|\r|\n|\n\r".replaceAll("(\r\n|\r|\n|\n\r)", "
")); }
}
//
|
|
|
</source>
Replaces all occourances of given character with new one and returns new String object.
<source lang="java">
public class Main {
public static void main(String args[]) { String str = "This is a test."; System.out.println(str.replace("T", "A")); }
} //Ahis is a test.</source>
Replaces all occourances of given String with new one and returns new String object.
<source lang="java">
public class Main {
public static void main(String args[]) { String str = "This is a test."; System.out.println(str.replaceAll("is", "are")); }
} //Thare are a test.</source>
Replaces only first occourances of given String with new one and returns new String object.
<source lang="java">
public class Main {
public static void main(String args[]) { String str = "This is a test."; System.out.println(str.replaceFirst("Th", "Ab")); }
} //Abis is a test.</source>
Replacing Characters in a String: replace() method creates a new string with the replaced characters.
<source lang="java">
public class Main {
public static void main(String[] argv) throws Exception { String string = "this is a string"; // Replace all occurrences of "a" with "o" String newString = string.replace("a", "o"); System.out.println(newString); }
}</source>
Replacing Substrings in a String
<source lang="java">
public class Main {
public static void main(String[] argv) throws Exception { System.out.println(replace("this is a test", "is", "are")); } static String replace(String str, String pattern, String replace) { int start = 0; int index = 0; StringBuffer result = new StringBuffer(); while ((index = str.indexOf(pattern, start)) >= 0) { result.append(str.substring(start, index)); result.append(replace); start = index + pattern.length(); } result.append(str.substring(start)); return result.toString(); }
}</source>
Returns a new string with all the whitespace removed
<source lang="java">
import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.util.Map;
/*
* JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */
public class Main{
/** * Returns a new string with all the whitespace removed * * @param s the source string * @return the string without whitespace or null */ public static String removeWhiteSpace(String s) { String retn = null; if (s != null) { int len = s.length(); StringBuffer sbuf = new StringBuffer(len); for (int i = 0; i < len; i++) { char c = s.charAt(i); if (!Character.isWhitespace(c)) sbuf.append(c); } retn = sbuf.toString(); } return retn; }
}</source>
String.Replace
<source lang="java">
public class MainClass {
public static void main( String args[] ) { String s1 = new String( "hello" ); String s2 = new String( "GOODBYE" ); String s3 = new String( " spaces " ); System.out.printf( "s1 = %s\ns2 = %s\ns3 = %s\n\n", s1, s2, s3 ); // test method replace System.out.printf("Replace "l" with "L" in s1: %s\n\n", s1.replace( "l", "L" ) );
} // end main
}</source>
s1 = hello s2 = GOODBYE s3 = spaces Replace "l" with "L" in s1: heLLo
To remove whitespace from the beginning and end of a string (but not the interior)
<source lang="java">
public class MainClass {
public static void main(String[] arg) { String sample = " This is a string "; String result = sample.trim(); System.out.println(">"+sample+"<"); System.out.println(">"+result+"<"); }
}</source>
> This is a string < >This is a string<
To replace a character at a specified position
<source lang="java">
public class Main {
public static void main(String args[]) { String str = "this is a test"; System.out.println(replaceCharAt(str, 5, "c")); } public static String replaceCharAt(String s, int pos, char c) { return s.substring(0, pos) + c + s.substring(pos + 1); }
} //this cs a test</source>
To replace one specific character with another throughout a string
<source lang="java">
public class MainClass {
public static void main(String[] arg) { String text = "To be or not to be, that is the question."; String newText = text.replace(" ", "/"); // Modify the string text System.out.println(newText); }
}</source>
To/be/or/not/to/be,/that/is/the/question.
Unaccent letters
<source lang="java">
import java.text.Normalizer; public class Main {
public static void main(String args[]) throws Exception { System.out.println(formatString("é")); } public static String formatString(String s) { String temp = Normalizer.normalize(s, Normalizer.Form.NFD); return temp.replaceAll("[^\\p{ASCII}]", ""); }
}</source>