Java/Data Type/String replace
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
- 1 Find, replace and remove strings
- 2 Java Implementation of Pythons string.replace()
- 3 Only replace first occurence
- 4 Optimize String operations
- 5 Remove leading whitespace a String using regular expressions
- 6 Remove leading white space from a string
- 7 Remove trailing whitespace
- 8 Replace characters in string
- 9 Replace every occurrences of a string within a string
- 10 Replace multiple whitespaces between words with single blank
- 11 Replace New Lines
- 12 Replace/remove character in a String: replace all occurrences of a given character
- 13 Replace \r\n with the tag
- 14 Replaces all instances of oldString with newString in string
- 15 Replaces all occurences of a substring inside a string
- 16 Replaces all occurrences of given character with new one and returns new String object.
- 17 Replaces all occurrences of given String with new one and returns new String object.
- 18 Replaces each substring of this string that matches toReplace
- 19 Replaces only first occurrences of given String with new one and returns new String object.
- 20 Replaces substrings
- 21 Replace string
- 22 Replace strings
- 23 Replace substrings within string
- 24 Replacing Characters in a String: replace() method creates a new string with the replaced characters.
- 25 Replacing Substrings in a String
- 26 String Replace
- 27 String Replace 2
- 28 String.replaceAll() can be used with String
- 29 Substitute sub-strings in side of a string
- 30 To replace a character at a specified position
- 31 Unaccent letters
Find, replace and remove strings
package net.firstpartners.nounit.utility;
/**
* Title: NoUnit - Identify Classes that are not being unit Tested
*
* Copyright (C) 2001 Paul Browne , FirstPartners.net
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* @author Paul Browne
* @version 0.6
*/
import java.sql.*;
import java.io.*;
import java.util.*;
import java.text.DateFormat.*;
/**
* Performs common , but tricky tasks.
* e.g. Stripping of spaces from Files
*/
public class TextUtil {
/**
* Replace the first occurrence of <code>oldSubstring</code> in
* <code>string</code>, if there is one, with <code>newSubstring</code>.
*
* @param string - Replace a substring of this String
* @param oldSubstring - The substring of <code>string</code> to be replaced
* @param newSubstring - The string to put into <code> string</code>
* @return A new String which is a copy of <code>string</code> with the first
* occurrence of <code>oldSubstring</code> in <code>string</code>, if
* there is one, with <code>newSubstring</code>.
* Returns null if <code>string</code> is null.
* Returns <code>string</code> if either substring is null or
* <code>oldSubstring</code> is empty
*/
public static String replace(String string,
String oldSubstring,
String newSubstring) {
String result = string;
if ((string != null) && (string.length() > 0)
&& (oldSubstring != null) && (oldSubstring.length() > 0)
&& (newSubstring != null))
{
int pos = string.indexOf(oldSubstring);
result = string.substring(0, pos)
+ newSubstring
+ string.substring(pos + oldSubstring.length());
}
return result;
}
/**
* Replaces all occurrences of <code>oldSubstring</code> in
* <code>string</code>, if there are any, with <code>newSubstring</code>.
*
* @param string - Replace substrings of this String
* @param oldSubstring - The substring of <code>string</code> to be replaced
* @param newSubstring - The string to put into <code> string</code>
* @return A new String which is a copy of <code>string</code> with all
* occurrences of <code>oldSubstring</code> in <code>string</code>,
* if there are any, with <code>newSubstring</code>.
* Returns null if <code>string</code> is null.
* Returns <code>string</code> if either substring is null or
* <code>oldSubstring</code> is empty
*/
public static String replaceAll( String string,
String oldSubstring,
String newSubstring) {
//Local Variables
String result = string;
if ( (result != null)
&& (result.length() > 0)
&& (result.indexOf(oldSubstring)>-1)
&& (oldSubstring.length() > 0)
&& (!oldSubstring.equals(newSubstring))) {
while (result.indexOf(oldSubstring) > -1) {
result = replace(result, oldSubstring, newSubstring);
}
}
return result;
}
/**
* Finds (start and end) markers in piece of text
* extracts text (note including markers) in between
* @param fullText to search in
* @param startIndex ignore text before this point
* @param startMarker start marker for the piece of text to extract
* @param endMarker end marker
* @return foundText , empty String if nothing found
*/
public static String find(String fullText,
int startIndex,
String startMarker,
String endMarker) {
//Local Variables
int startPlace=0;
int endPlace=0;
String foundText="";
//Find the first instance of text
startPlace = fullText.indexOf(startMarker,startIndex)
+startMarker.length();
//Find the first instance of end marker after this
if (startPlace > startIndex) {
startIndex = startPlace;
}
endPlace = fullText.indexOf(endMarker,startIndex);
//Copy and return
try {
if ((startPlace>-1) || (endPlace>-1)) {
foundText=fullText.substring(startPlace,endPlace);
}
} catch (java.lang.StringIndexOutOfBoundsException sioobe) {
// do nothing - will return default of empty string
}
//Ensure that there are no dodgy strings..
if (startPlace<startIndex) {
foundText="";
}
return foundText;
}
/**
* Remove all instances of input string from Output
* @param inputString
* @param removeString
* @return updateString
*/
public static String removeAll(String inputString,
String removeString) {
//Internal Variables
StringBuffer updateString = new StringBuffer();
String tmpString;
for(int a=0; a<inputString.length(); a++ ) {
tmpString = inputString.substring(a,a+1);
if (!tmpString.equals(removeString)) {
updateString.append(tmpString);
}
}
return updateString.toString();
}
/**
* Strip out any trailing characters
* @param inString to be operated on
* @param toRemove string to remove at end if found
* @return inString with end removed
*/
public static String removeTrailing (String inString,
String toRemove) {
while (inString.endsWith(toRemove)) {
inString=inString.substring(0,inString.length()-toRemove.length());
}
return inString;
}
}
Java Implementation of Pythons string.replace()
import java.io.File;
import java.util.ArrayList;
/*
* IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
*
* http://izpack.org/
* http://izpack.codehaus.org/
*
* Copyright 2003 Marc Eppelmann
*
* 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.
*/
/**
* A extended Java Implementation of Pythons string.replace()
*
* @author marc.eppelmann@gmx.de
*/
class StringTool
{
// ~ Constructors
// *********************************************************************************
/**
* Default Constructor
*/
public StringTool()
{
super();
}
// ~ Methods
// **************************************************************************************
/**
* Standalone callable Test method
*
* @param args Commandline Args
*/
public static void main(String[] args)
{
System.out.println("Test: string.replace(abc$defg,$de ,null ):"
+ StringTool.replace("abc$defg", "$de", null, true));
}
/**
* Replaces <b>from</b> with <b>to</b> in given String: <b>value</b>
*
* @param value original String
* @param from Search Pattern
* @param to Replace with this
* @return the replaced String
*/
public static String replace(String value, String from, String to)
{
return replace(value, from, to, true);
}
/**
* Replaces <b>from</b> with <b>to</b> in given String: <b>value</b>
*
* @param value original String
* @param from Search Pattern
* @param to Replace with this
* @param aCaseSensitiveFlag set to true be case sensitive.
* @return the replaced String
*/
public static String replace(String value, String from, String to, boolean aCaseSensitiveFlag)
{
if ((value == null) || (value.length() == 0) || (from == null) || (from.length() == 0))
{
return value;
}
if (to == null)
{
to = "";
}
if (!aCaseSensitiveFlag)
{
from = from.toLowerCase();
}
String result = value;
int lastIndex = 0;
int index = value.indexOf(from);
if (index != -1)
{
StringBuffer buffer = new StringBuffer();
while (index != -1)
{
buffer.append(value.substring(lastIndex, index)).append(to);
lastIndex = index + from.length();
index = value.indexOf(from, lastIndex);
}
buffer.append(value.substring(lastIndex));
result = buffer.toString();
}
return result;
}
/**
* Escapes all white Space Characters
* @param apathString
* @return
*/
public static String escapeSpaces( String aPathString )
{
return replaceOrEscapeAll( aPathString, null, null, true );
}
/**
* Escapes all white Space Characters
* @param apathString
* @return
*/
public static String replaceSpacesWithMinus( String aPathString )
{
return replaceSpaces( aPathString, "-" );
}
/**
* Escapes all white Space Characters
* @param apathString
* @return
*/
public static String replaceSpaces( String aPathString, String replaceWith )
{
return replaceOrEscapeAll( aPathString, replaceWith, null, false );
}
/**
* Replaces all given white Space Characters with the replaceOrEscapeWith or Escapes with replaceOrEscapeWith
*
* If true was given as Escape-Flag , the Method escapes each whitespace with the replaceOrEscapeWith + replaceWhat[x]
* Otherwise the replaces each replaceWhat[x] with the replaceOrEscapeWith.
*
* @param aPathString The input string in which the white space should be handled.
* @param replaceOrEscapeWith The Repace or Escape Char Interpreted depended on the escape Flag
* @param replaceWhat The atring array with the Characters, which should be replaced
* @param escape The flag, wihch indeicates, how to handle the given replaceOrEscapeWith String.
*
*/
public static String replaceOrEscapeAll( String aPathString, String replaceOrEscapeWith, String[] replaceWhat, boolean escape )
{
if( replaceWhat == null )
replaceWhat = new String[]{" ", "\t", "\n"};
if( replaceOrEscapeWith == null )
replaceOrEscapeWith = "\\";
for (int i = 0; i < replaceWhat.length; i++)
{
aPathString = replace(aPathString, replaceWhat[i], escape == true ? replaceOrEscapeWith + replaceWhat[i]: replaceOrEscapeWith );
}
return aPathString;
}
/**
* Normalizes a Windows or Unix Path.
* <p/>
* Reason: Javas File accepts / or \ for Pathes. Batches or ShellScripts does it not!
* <p/>
* TODO: implement support for MAC < MacOSX
*
* @param destination
* @param fileSeparator a target-system fileseparator
* @return the normalized path
*/
public static String normalizePath(String destination, String fileSeparator)
{
String FILESEP = (fileSeparator == null) ? File.separator : fileSeparator;
destination = StringTool.replace(destination, "\\", "/");
// all occs of "//" by "/"
destination = StringTool.replace(destination, "//", "/");
destination = StringTool.replace(destination, ":", ";");
destination = StringTool.replace(destination, ";", ":");
destination = StringTool.replace(destination, "/", FILESEP);
if ("\\".equals(FILESEP))
{
destination = StringTool.replace(destination, ":", ";");
// results in "C;\" instead of "C:\"
// so correct it:
destination = StringTool.replace(destination, ";\\", ":\\");
}
// Convert the file separator characters
return (destination);
}
/**
* Normalizes a mixed Windows/Unix Path. Does Only work for Windows or Unix Pathes Reason:
* Java.File accepts / or \ for Pathes. Batches or ShellScripts does it not!
*
* @param destination accepted mixed form by java.File like "C:/a/mixed\path\accepted/by\Java"
* @return the normalized Path
*/
public static String normalizePath(String destination)
{
return (normalizePath(destination, null));
}
/**
* Converts an String Array to a space separated String w/o any check
*
* @param args The StringArray
* @return the space separated result.
*/
public static String stringArrayToSpaceSeparatedString(String[] args)
{
String result = "";
for (String arg : args)
{
result += arg + " ";
}
return result;
}
public static String getPlatformEncoding()
{
// TODO Auto-generated method stub
return System.getProperty("file.encoding");
}
public static String UTF16()
{
return "UTF-16";
}
/**
* Transforms a (Array)List of Strings into a line.separator="\n" separated Stringlist.
*
* @param aStringList
* @return a printable list
*/
public static String stringArrayListToString(ArrayList aStringList)
{
return stringArrayListToString(aStringList, null);
}
/**
* Transforms a (Array)List of Strings into an aLineSeparator separated Stringlist.
*
* @param aStringList
* @return a printable list
*/
public static String stringArrayListToString(ArrayList aStringList, String aLineSeparator)
{
String LineSeparator = aLineSeparator;
if (LineSeparator == null)
{
LineSeparator = System.getProperty("line.separator", "\n");
}
StringBuffer temp = new StringBuffer();
for (Object anAStringList : aStringList)
{
temp.append(anAStringList).append(LineSeparator);
}
return temp.toString();
}
/**
* True if a given string starts with the another given String
*
* @param str The String to search in
* @param prefix The string to search for
* @return True if str starts with prefix
*/
public static boolean startsWith(String str, String prefix)
{
return (str != null) && str.startsWith(prefix);
}
/**
* The same as startsWith but ignores the case.
*
* @param str The String to search in
* @param prefix The string to search for
* @return rue if str starts with prefix
*/
public static boolean startsWithIgnoreCase(String str, String prefix)
{
return (str != null) && (prefix != null)
&& str.toUpperCase().startsWith(prefix.toUpperCase());
}
}
/////////////////////////////////////////
/*
* IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
*
* http://izpack.org/
* http://izpack.codehaus.org/
*
* 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.
*/
package com.izforge.izpack.util;
import junit.framework.TestCase;
public class StringToolTest extends TestCase
{
/*
* Class under test for String replace(String, String, String[, boolean])
*/
public void testReplace()
{
String ref = "ABC-012-def";
TestCase.assertEquals(null, StringTool.replace(null, null, null));
TestCase.assertEquals("ABC-012-def", StringTool.replace(ref, null, null));
TestCase.assertEquals("ABC-012-def", StringTool.replace(ref, "something", null));
TestCase.assertEquals("ABC012def", StringTool.replace(ref, "-", null));
TestCase.assertEquals("abc-012-def", StringTool.replace(ref, "ABC", "abc"));
TestCase.assertEquals("ABC-012-def", StringTool.replace(ref, "abc", "abc", false));
TestCase.assertEquals("ABC-012-def", StringTool.replace(ref, "abc", "abc", true));
}
/*
* Class under test for String normalizePath(String[, String])
*/
public void testNormalizePath()
{
TestCase.assertEquals("C:\\Foo\\Bar\\is\\so\\boring;plop;plop", StringTool.normalizePath(
"C:\\Foo/Bar/is\\so\\boring:plop;plop", "\\"));
TestCase.assertEquals("/some/where/that:matters:really", StringTool.normalizePath(
"/some/where\\that:matters;really", "/"));
}
}
Only replace first occurence
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
Optimize String operations
public class Main {
public static void main(String args[]) throws Exception {
String str = "this is a test";
System.out.println(replaceCharAt(str, 0, "d"));
}
public static String replaceCharAt(String s, int pos, char c) {
StringBuffer buf = new StringBuffer(s);
buf.setCharAt(pos, c);
return buf.toString();
}
}
//dhis is a test
Remove leading whitespace a String using regular expressions
public class Main {
public static void main(String[] argv) {
String s = " this is a test ";
s.replaceAll("^\\s+", "");
System.out.println(">" + s + "<");
}
}
//> this is a test <
Remove leading white space from a string
public class Main {
public static void main(String[] args) {
String text = " t ";
text = text.replaceAll("^\\s+", "");
System.out.println("Text: " + text);
}
}
Remove trailing whitespace
public class Main {
public static void main(String[] argv) {
System.out.println(">" + " asdf ".replaceAll("\\s+$", "") + "<");
}
}
// > asdf<
Replace characters in string
public class Main {
public static void main(String[] args) {
String text = "The quick brown fox jumps over the lazy dog";
text = text.replace("o", "u");
System.out.println("Result: " + text);
}
}
Replace every occurrences of a string within a string
public class Main {
public static void main(String[] args) {
String text = "a b c e a b";
System.out.println(text.replaceAll("(?:a b)+", "x y"));
}
}
//x y c e x y
Replace multiple whitespaces between words with single blank
public class Main {
public static void main(String[] argv) {
System.out.println(">" + " asdf ".replaceAll("\\b\\s{2,}\\b", " ") + "<");
}
}
//> asdf <
Replace New Lines
/*
* Copyright 2000,2005 wingS development team.
*
* This file is part of wingS (http://wingsframework.org).
*
* wingS 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.
*
* Please see COPYING for the complete licence.
*/
import java.util.StringTokenizer;
/**
* Some string manipulation utilities.
*
* @author
*/
public class StringUtil {
/**
* replaces all newlines in the given String "s" with the replacement
* string "r". Each line is trimmed from leading and trailing whitespaces,
* then the new line-delimiter is added.
*
* @param s the source string.
* @param r the new line delimiter
* @return the resulting string.
*/
public static final String replaceNewLines(String s, String r) {
StringBuilder result = new StringBuilder();
StringTokenizer t = new StringTokenizer(s, "\n");
while (t.hasMoreTokens()) {
result.append(t.nextToken().trim()).append(r);
}
return result.toString();
}
}
Replace/remove character in a String: replace all occurrences of a given character
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 = ***
*/
Replace \r\n with the
tag
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)", "<br>"));
}
}
//<br>|<br>|<br>|<br><br>
Replaces all instances of oldString with newString in string
/**
* $Revision: 10205 $
* $Date: 2008-04-11 15:48:27 -0700 (Fri, 11 Apr 2008) $
*
* Copyright (C) 2004-2008 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution, or a commercial license
* agreement with Jive.
*/
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.BreakIterator;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* Utility class to peform common String manipulation algorithms.
*/
public class StringUtils {
// Constants used by escapeHTMLTags
private static final char[] QUOTE_ENCODE = """.toCharArray();
private static final char[] AMP_ENCODE = "&".toCharArray();
private static final char[] LT_ENCODE = "<".toCharArray();
private static final char[] GT_ENCODE = ">".toCharArray();
private StringUtils() {
// Not instantiable.
}
/**
* Replaces all instances of oldString with newString in string.
*
* @param string the String to search to perform replacements on.
* @param oldString the String that should be replaced by newString.
* @param newString the String that will replace all instances of oldString.
* @return a String will all instances of oldString replaced by newString.
*/
public static String replace(String string, String oldString, String newString) {
if (string == null) {
return null;
}
int i = 0;
// Make sure that oldString appears at least once before doing any processing.
if ((i = string.indexOf(oldString, i)) >= 0) {
// Use char []"s, as they are more efficient to deal with.
char[] string2 = string.toCharArray();
char[] newString2 = newString.toCharArray();
int oLength = oldString.length();
StringBuilder buf = new StringBuilder(string2.length);
buf.append(string2, 0, i).append(newString2);
i += oLength;
int j = i;
// Replace all remaining instances of oldString with newString.
while ((i = string.indexOf(oldString, i)) > 0) {
buf.append(string2, j, i - j).append(newString2);
i += oLength;
j = i;
}
buf.append(string2, j, string2.length - j);
return buf.toString();
}
return string;
}
/**
* Replaces all instances of oldString with newString in line with the
* added feature that matches of newString in oldString ignore case.
*
* @param line the String to search to perform replacements on
* @param oldString the String that should be replaced by newString
* @param newString the String that will replace all instances of oldString
* @return a String will all instances of oldString replaced by newString
*/
public static String replaceIgnoreCase(String line, String oldString,
String newString) {
if (line == null) {
return null;
}
String lcLine = line.toLowerCase();
String lcOldString = oldString.toLowerCase();
int i = 0;
if ((i = lcLine.indexOf(lcOldString, i)) >= 0) {
char[] line2 = line.toCharArray();
char[] newString2 = newString.toCharArray();
int oLength = oldString.length();
StringBuilder buf = new StringBuilder(line2.length);
buf.append(line2, 0, i).append(newString2);
i += oLength;
int j = i;
while ((i = lcLine.indexOf(lcOldString, i)) > 0) {
buf.append(line2, j, i - j).append(newString2);
i += oLength;
j = i;
}
buf.append(line2, j, line2.length - j);
return buf.toString();
}
return line;
}
/**
* Replaces all instances of oldString with newString in line with the
* added feature that matches of newString in oldString ignore case.
* The count paramater is set to the number of replaces performed.
*
* @param line the String to search to perform replacements on
* @param oldString the String that should be replaced by newString
* @param newString the String that will replace all instances of oldString
* @param count a value that will be updated with the number of replaces
* performed.
* @return a String will all instances of oldString replaced by newString
*/
public static String replaceIgnoreCase(String line, String oldString,
String newString, int[] count)
{
if (line == null) {
return null;
}
String lcLine = line.toLowerCase();
String lcOldString = oldString.toLowerCase();
int i = 0;
if ((i = lcLine.indexOf(lcOldString, i)) >= 0) {
int counter = 1;
char[] line2 = line.toCharArray();
char[] newString2 = newString.toCharArray();
int oLength = oldString.length();
StringBuilder buf = new StringBuilder(line2.length);
buf.append(line2, 0, i).append(newString2);
i += oLength;
int j = i;
while ((i = lcLine.indexOf(lcOldString, i)) > 0) {
counter++;
buf.append(line2, j, i - j).append(newString2);
i += oLength;
j = i;
}
buf.append(line2, j, line2.length - j);
count[0] = counter;
return buf.toString();
}
return line;
}
/**
* Replaces all instances of oldString with newString in line.
* The count Integer is updated with number of replaces.
*
* @param line the String to search to perform replacements on.
* @param oldString the String that should be replaced by newString.
* @param newString the String that will replace all instances of oldString.
* @return a String will all instances of oldString replaced by newString.
*/
public static String replace(String line, String oldString,
String newString, int[] count)
{
if (line == null) {
return null;
}
int i = 0;
if ((i = line.indexOf(oldString, i)) >= 0) {
int counter = 1;
char[] line2 = line.toCharArray();
char[] newString2 = newString.toCharArray();
int oLength = oldString.length();
StringBuilder buf = new StringBuilder(line2.length);
buf.append(line2, 0, i).append(newString2);
i += oLength;
int j = i;
while ((i = line.indexOf(oldString, i)) > 0) {
counter++;
buf.append(line2, j, i - j).append(newString2);
i += oLength;
j = i;
}
buf.append(line2, j, line2.length - j);
count[0] = counter;
return buf.toString();
}
return line;
}
}
Replaces all occurences of a substring inside a string
/**************************************************************************************
* Copyright (c) Jonas Bon�r, Alexandre Vasseur. All rights reserved. *
* http://aspectwerkz.codehaus.org *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the LGPL license *
* a copy of which has been included with this distribution in the license.txt file. *
**************************************************************************************/
import java.util.List;
import java.util.ArrayList;
/**
* Utility methods for strings.
*
* @author
*/
public class Strings {
/**
* Replaces all occurences of a substring inside a string.
*
* @param str the string to search and replace in
* @param oldToken the string to search for
* @param newToken the string to replace newToken
* @return the new string
*/
public static String replaceSubString(final String str, final String oldToken, final String newToken) {
return replaceSubString(str, oldToken, newToken, -1);
}
/**
* Replaces all occurences of a substring inside a string.
*
* @param str the string to search and replace in
* @param oldToken the string to search for
* @param newToken the string to replace newToken
* @param max maximum number of values to replace (-1 => no maximum)
* @return the new string
*/
public static String replaceSubString(final String str, final String oldToken, final String newToken, int max) {
if ((str == null) || (oldToken == null) || (newToken == null) || (oldToken.length() == 0)) {
return str;
}
StringBuffer buf = new StringBuffer(str.length());
int start = 0;
int end = 0;
while ((end = str.indexOf(oldToken, start)) != -1) {
buf.append(str.substring(start, end)).append(newToken);
start = end + oldToken.length();
if (--max == 0) {
break;
}
}
buf.append(str.substring(start));
return buf.toString();
}
}
Replaces all occurrences of given character with new one and returns new String object.
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.
Replaces all occurrences of given String with new one and returns new String object.
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.
Replaces each substring of this string that matches toReplace
/**********************************************************************
Copyright (c) 2003 Andy Jefferson and others. All rights reserved.
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.
Contributors:
2003 Erik Bengtson - moved replaceAll from Column class to here
2004 Andy Jefferson - moved intArrayToString, booleanArrayToString from SM
2007 Xuan Baldauf - toJVMIDString hex fix
...
**********************************************************************/
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URLDecoder;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.jar.JarFile;
/**
* Utilities for String manipulation.
*
* @version $Revision: 1.23 $
**/
public class StringUtils
{
/**
* Replaces each substring of this string that matches toReplace.
* Used to replace replaceAll when using J2SDK 1.3.1.
* This method is available at String.replaceAll in J2SDK 1.4
* @param theString The string to use
* @param toReplace The string to replace.
* @param replacement The replacement string.
* @return The updated string after replacing.
*/
public static String replaceAll(String theString, String toReplace, String replacement)
{
if (theString == null)
{
return null;
}
if (theString.indexOf(toReplace) == -1)
{
return theString;
}
StringBuffer stringBuffer = new StringBuffer(theString);
int index = theString.length();
int offset = toReplace.length();
while ((index=theString.lastIndexOf(toReplace, index-1)) > -1)
{
stringBuffer.replace(index,index+offset, replacement);
}
return stringBuffer.toString();
}
}
Replaces only first occurrences of given String with new one and returns new String object.
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.
Replaces substrings
/*
* Copyright 2000,2005 wingS development team.
*
* This file is part of wingS (http://wingsframework.org).
*
* wingS 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.
*
* Please see COPYING for the complete licence.
*/
import java.util.StringTokenizer;
/**
* Some string manipulation utilities.
*
* @author
*/
public class StringUtil {
/**
* replaces substrings with content "toFind" with "replace" in
* s and returns the result ("s/$toFind/$replace/g")
*
* @param s The String the substrings should be replaced in.
* @param toFind The substring to be replaced
* @param replace The replacement.
* @return the string with all replacements.
*/
public static final String replace(String s,
String toFind, String replace) {
StringBuilder erg = new StringBuilder();
int lastindex = 0;
int indexOf = s.indexOf(toFind);
if (indexOf == -1) return s;
while (indexOf != -1) {
erg.append(s.substring(lastindex, indexOf)).append(replace);
lastindex = indexOf + toFind.length();
indexOf = s.indexOf(toFind, lastindex);
}
erg.append(s.substring(lastindex));
return erg.toString();
}
}
Replace string
/*
* Static String formatting and query routines.
* Copyright (C) 2001-2005 Stephen Ostermiller
* http://ostermiller.org/contact.pl?regarding=Java+Utilities
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* See COPYING.TXT for details.
*/
import java.util.HashMap;
import java.util.regex.Pattern;
/**
* Utilities for String formatting, manipulation, and queries.
* More information about this class is available from .
*
* @author Stephen Ostermiller http://ostermiller.org/contact.pl?regarding=Java+Utilities
* @since ostermillerutils 1.00.00
*/
public class StringHelper {
/**
* Replace occurrences of a substring.
*
* StringHelper.replace("1-2-3", "-", "|");<br>
* result: "1|2|3"<br>
* StringHelper.replace("-1--2-", "-", "|");<br>
* result: "|1||2|"<br>
* StringHelper.replace("123", "", "|");<br>
* result: "123"<br>
* StringHelper.replace("1-2---3----4", "--", "|");<br>
* result: "1-2|-3||4"<br>
* StringHelper.replace("1-2---3----4", "--", "---");<br>
* result: "1-2----3------4"<br>
*
* @param s String to be modified.
* @param find String to find.
* @param replace String to replace.
* @return a string with all the occurrences of the string to find replaced.
* @throws NullPointerException if s is null.
*
* @since ostermillerutils 1.00.00
*/
public static String replace(String s, String find, String replace){
int findLength;
// the next statement has the side effect of throwing a null pointer
// exception if s is null.
int stringLength = s.length();
if (find == null || (findLength = find.length()) == 0){
// If there is nothing to find, we won"t try and find it.
return s;
}
if (replace == null){
// a null string and an empty string are the same
// for replacement purposes.
replace = "";
}
int replaceLength = replace.length();
// We need to figure out how long our resulting string will be.
// This is required because without it, the possible resizing
// and copying of memory structures could lead to an unacceptable runtime.
// In the worst case it would have to be resized n times with each
// resize having a O(n) copy leading to an O(n^2) algorithm.
int length;
if (findLength == replaceLength){
// special case in which we don"t need to count the replacements
// because the count falls out of the length formula.
length = stringLength;
} else {
int count;
int start;
int end;
// Scan s and count the number of times we find our target.
count = 0;
start = 0;
while((end = s.indexOf(find, start)) != -1){
count++;
start = end + findLength;
}
if (count == 0){
// special case in which on first pass, we find there is nothing
// to be replaced. No need to do a second pass or create a string buffer.
return s;
}
length = stringLength - (count * (findLength - replaceLength));
}
int start = 0;
int end = s.indexOf(find, start);
if (end == -1){
// nothing was found in the string to replace.
// we can get this if the find and replace strings
// are the same length because we didn"t check before.
// in this case, we will return the original string
return s;
}
// it looks like we actually have something to replace
// *sigh* allocate memory for it.
StringBuffer sb = new StringBuffer(length);
// Scan s and do the replacements
while (end != -1){
sb.append(s.substring(start, end));
sb.append(replace);
start = end + findLength;
end = s.indexOf(find, start);
}
end = stringLength;
sb.append(s.substring(start, end));
return (sb.toString());
}
}
Replace strings
/*
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.Properties;
import java.util.Random;
public class StringUtils
{
/**
* Replaces the relevant entities inside the String.
* All & >, <, and " are replaced by their
* respective names.
*
* @since 1.6.1
* @param src The source string.
* @return The encoded string.
*/
public static String replaceEntities( String src )
{
src = replaceString( src, "&", "&" );
src = replaceString( src, "<", "<" );
src = replaceString( src, ">", ">" );
src = replaceString( src, "\"", """ );
return src;
}
/**
* Replaces a string with an other string.
*
* @param orig Original string. Null is safe.
* @param src The string to find.
* @param dest The string to replace <I>src</I> with.
* @return A string with the replacement done.
*/
public static final String replaceString( String orig, String src, String dest )
{
if ( orig == null ) return null;
if ( src == null || dest == null ) throw new NullPointerException();
if ( src.length() == 0 ) return orig;
StringBuffer res = new StringBuffer(orig.length()+20); // Pure guesswork
int start = 0;
int end = 0;
int last = 0;
while ( (start = orig.indexOf(src,end)) != -1 )
{
res.append( orig.substring( last, start ) );
res.append( dest );
end = start+src.length();
last = start+src.length();
}
res.append( orig.substring( end ) );
return res.toString();
}
/**
* Replaces a part of a string with a new String.
*
* @param start Where in the original string the replacing should start.
* @param end Where the replacing should end.
* @param orig Original string. Null is safe.
* @param text The new text to insert into the string.
* @return The string with the orig replaced with text.
*/
public static String replaceString( String orig, int start, int end, String text )
{
if( orig == null ) return null;
StringBuffer buf = new StringBuffer(orig);
buf.replace( start, end, text );
return buf.toString();
}
/**
* Replaces a string with an other string. Case insensitive matching is used
*
* @param orig Original string. Null is safe.
* @param src The string to find.
* @param dest The string to replace <I>src</I> with.
* @return A string with all instances of src replaced with dest.
*/
public static String replaceStringCaseUnsensitive( String orig, String src, String dest )
{
if( orig == null ) return null;
StringBuffer res = new StringBuffer();
int start = 0;
int end = 0;
int last = 0;
String origCaseUnsn = orig.toLowerCase();
String srcCaseUnsn = src.toLowerCase();
while( (start = origCaseUnsn.indexOf(srcCaseUnsn, end)) != -1 )
{
res.append( orig.substring( last, start ) );
res.append( dest );
end = start+src.length();
last = start+src.length();
}
res.append( orig.substring( end ) );
return res.toString();
}
}
Replace substrings within string
//
// 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
{
/**
* replace substrings within string.
*/
public static String replace(String s, String sub, String with)
{
int c=0;
int i=s.indexOf(sub,c);
if (i == -1)
return s;
StringBuffer buf = new StringBuffer(s.length()+with.length());
synchronized(buf)
{
do
{
buf.append(s.substring(c,i));
buf.append(with);
c=i+sub.length();
} while ((i=s.indexOf(sub,c))!=-1);
if (c<s.length())
buf.append(s.substring(c,s.length()));
return buf.toString();
}
}
}
Replacing Characters in a String: replace() method creates a new string with the replaced characters.
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);
}
}
Replacing Substrings in a String
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();
}
}
String Replace
/*
* 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.
*/
public class Replace {
public static void main(String[] args) {
System.out.println(
replace("lazy", "supine", "A quick bronze fox lept a lazy bovine"));
System.out.println(
replace("$DIR", "/home/ian", "$DIR/xxx"));
}
public static String replace(String oldStr, String newStr, String inString) {
int start = inString.indexOf(oldStr);
if (start == -1) {
return inString;
}
StringBuffer sb = new StringBuffer();
sb.append(inString.substring(0, start));
sb.append(newStr);
sb.append(inString.substring(start+oldStr.length()));
return sb.toString();
}
}
String Replace 2
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution 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.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
// This example demonstrates the use of the replace method
//in the String class.
public class BostonAccentDemo {
private static void bostonAccent(String sentence) {
char r = "r";
char h = "h";
String translatedSentence = sentence.replace(r, h);
System.out.println(translatedSentence);
}
public static void main(String[] args) {
String translateThis = "Park the car in Harvard yard.";
bostonAccent(translateThis);
}
}
String.replaceAll() can be used with String
public class Main {
public static void main(String args[]) {
// Remove all \n with empty string
System.out.println("\r\n\t\b".replaceAll("\n", ""));
// Replace \n by \r
System.out.println("\r\n\t\b".replaceAll("\n", "\r"));
}
}
Substitute sub-strings in side of a string
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{
/** An empty string constant */
public static final String EMPTY = "";
/////////////////////////////////////////////////////////////////////////
// Substitution Methods //
/////////////////////////////////////////////////////////////////////////
/**
* Substitute sub-strings in side of a string.
*
* @param buff Stirng buffer to use for substitution (buffer is not reset)
* @param from String to substitute from
* @param to String to substitute to
* @param string String to look for from in
* @return Substituted string
*/
public static String subst(final StringBuffer buff, final String from,
final String to, final String string)
{
int begin = 0, end = 0;
while ((end = string.indexOf(from, end)) != -1)
{
// append the first part of the string
buff.append(string.substring(begin, end));
// append the replaced string
buff.append(to);
// update positions
begin = end + from.length();
end = begin;
}
// append the rest of the string
buff.append(string.substring(begin, string.length()));
return buff.toString();
}
/**
* Substitute sub-strings in side of a string.
*
* @param from String to substitute from
* @param to String to substitute to
* @param string String to look for from in
* @return Substituted string
*/
public static String subst(final String from, final String to,
final String string)
{
return subst(new StringBuffer(), from, to, string);
}
/**
* Substitute sub-strings in side of a string.
*
* @param buff String buffer to use for substitution (buffer is not reset)
* @param string String to subst mappings in
* @param map Map of from->to strings
* @param beginToken Beginning token
* @param endToken Ending token
* @return Substituted string
*/
public static String subst(final StringBuffer buff, final String string,
final Map map, final String beginToken,
final String endToken)
{
int begin = 0, rangeEnd = 0;
Range range;
while ((range = rangeOf(beginToken, endToken, string, rangeEnd)) != null)
{
// append the first part of the string
buff.append(string.substring(begin, range.begin));
// Get the string to replace from the map
String key = string.substring(range.begin + beginToken.length(),
range.end);
Object value = map.get(key);
// if mapping does not exist then use empty;
if (value == null) value = EMPTY;
// append the replaced string
buff.append(value);
// update positions
begin = range.end + endToken.length();
rangeEnd = begin;
}
// append the rest of the string
buff.append(string.substring(begin, string.length()));
return buff.toString();
}
/**
* Substitute sub-strings in side of a string.
*
* @param string String to subst mappings in
* @param map Map of from->to strings
* @param beginToken Beginning token
* @param endToken Ending token
* @return Substituted string
*/
public static String subst(final String string, final Map map,
final String beginToken, final String endToken)
{
return subst(new StringBuffer(), string, map, beginToken, endToken);
}
/**
* Substitute index identifiers with the replacement value from the
* given array for the corresponding index.
*
* @param buff The string buffer used for the substitution
* (buffer is not reset).
* @param string String substitution format.
* @param replace Array of strings whose values will be used as
* replacements in the given string when a token with
* their index is found.
* @param token The character token to specify the start of an index
* reference.
* @return Substituted string.
*/
public static String subst(final StringBuffer buff, final String string,
final String replace[], final char token)
{
int i = string.length();
for (int j = 0; j >= 0 && j < i; j++)
{
char c = string.charAt(j);
// if the char is the token, then get the index
if (c == token)
{
// if we aren"t at the end of the string, get the index
if (j != i)
{
int k = Character.digit(string.charAt(j + 1), 10);
if (k == -1)
{
buff.append(string.charAt(j + 1));
}
else if (k < replace.length)
{
buff.append(replace[k]);
}
j++;
}
}
else
{
buff.append(c);
}
}
return buff.toString();
}
/**
* Substitute index identifiers with the replacement value from the
* given array for the corresponding index.
*
* @param string String substitution format.
* @param replace Array of strings whose values will be used as
* replacements in the given string when a token with
* their index is found.
* @param token The character token to specify the start of an index
* reference.
* @return Substituted string.
*/
public static String subst(final String string, final String replace[],
final char token)
{
return subst(new StringBuffer(), string, replace, token);
}
/**
* Substitute index identifiers (with <code>%</code> for the index token)
* with the replacement value from the given array for the corresponding
* index.
*
* @param string String substitution format.
* @param replace Array of strings whose values will be used as
* replacements in the given string when a token with
* their index is found.
* @return Substituted string.
*/
public static String subst(final String string, final String replace[])
{
return subst(new StringBuffer(), string, replace, "%");
}
/////////////////////////////////////////////////////////////////////////
// Range Methods //
/////////////////////////////////////////////////////////////////////////
/**
* Represents a range between two integers.
*/
public static class Range
{
/** The beginning of the range. */
public int begin;
/** The end of the range. */
public int end;
/**
* Construct a new range.
*
* @param begin The beginning of the range.
* @param end The end of the range.
*/
public Range(int begin, int end)
{
this.begin = begin;
this.end = end;
}
/**
* Default constructor.
*/
public Range()
{
}
}
/**
* Return the range from a begining token to an ending token.
*
* @param beginToken String to indicate begining of range.
* @param endToken String to indicate ending of range.
* @param string String to look for range in.
* @param fromIndex Beginning index.
* @return (begin index, end index) or <i>null</i>.
*/
public static Range rangeOf(final String beginToken, final String endToken,
final String string, final int fromIndex)
{
int begin = string.indexOf(beginToken, fromIndex);
if (begin != -1)
{
int end = string.indexOf(endToken, begin + 1);
if (end != -1)
{
return new Range(begin, end);
}
}
return null;
}
/**
* Return the range from a begining token to an ending token.
*
* @param beginToken String to indicate begining of range.
* @param endToken String to indicate ending of range.
* @param string String to look for range in.
* @return (begin index, end index) or <i>null</i>.
*/
public static Range rangeOf(final String beginToken, final String endToken,
final String string)
{
return rangeOf(beginToken, endToken, string, 0);
}
}
To replace a character at a specified position
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
Unaccent letters
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}]", "");
}
}