C++ equivalent of java StringBuilder.replace - java

What is the C++ equivalent of the following java function?
public StringBuilder replace(int start,
int end,
String str)
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html#replace(int,%20int,%20java.lang.String)

Here is the replace all function we are using,
string ReplaceAll(string original, string replaceThis, string replaceWith)
{
std::string::size_type pos = 0;
while((pos = original.find(replaceThis, pos)) != std::string::npos)
{
original.replace(pos, (replaceThis.length()), replaceWith);
pos += replaceWith.length();
}
return original;
}
You can also refer the following link for better understanding.
REPLACE IN C++

C++'s string::replace is pretty similar to what you're looking for. However, instead of finding the range you want to replace with the left and right integer indexes, you pass in string iterators.

Related

Java IF Statement necessary?

I have:
String str = "Hello, how, are, you";
I want to create a helper method that removes the commas from any string. Which of the following is more accurate?
private static String removeComma(String str){
if(str.contains(",")){
str = str.replaceAll(",","");
}
return str;
}
OR
private static String removeComma(String str){
str = str.replaceAll(",","");
return str;
}
Seems like I don't need the IF statement but there might be a case where I do.
If there is a better way let me know.
Both are functionally equivalent but the former is more verbose and will probably be slower because it runs an extra operation.
Also note that you don't need replaceAll (which accepts a regular expression): replace will do.
So I would go for:
private static String removeComma(String str){
return str.replace(",", "");
}
The IF statement is unnecessary, unless you're handling "large" strings (we're talking megabytes or more).
If you're using the IF statement, your code will first search for the first occurance of a comma, and then execute the replacement. This could be costly if the comma is near the end of the string and your string is large, since it will have to be traversed twice.
Without the IF statement, commas will be replaced if they exist. If the answer is negative, your string will be untouched.
Bottom rule: use the version without the IF statement.
Both are correct, but the second one is cleaner since the IF statement of the first alternative is not needed.
It's a matter of what is the probability to have strings with comma in your universe of strings.
If you have a high probability, call the method replaceAll without checking first.
BUT If you are not using extremely huge strings, I guess you will see no difference in perfomance at all.
Just another solution with time complexity O(n), space complexity O(n):
public static String removeComma(String str){
int length = str.length();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
char c = str.charAt(i);
if (c != ',') {
sb.append(c);
}
}
return sb.toString();
}

implementation for java substring with negative values

in java,
String month= "November 2014";
for making a substring giving the index from right hand side, I cannot use
someString.substring(-4);
as negative values are not supported.
Is there any simple implementation I can use to achieve this.
No, negative numbers are not allowed (it would throw a StringIndexOutOfBoundsException). You can use this:
if(month.length() >= 4) {
year = month.substring(month.length() - 4);
}
I love Python's indexing and prefer to be able to use it in Java as well ;)
A general implementation of substring with support for negative indexing could be implemented like this:
A method for converting negative indexes to their positive equivalent is useful:
private static int toPosIndex(String str, int index) {
if (index >= 0) return index;
else return str.length() + index;
This method can then be used to declare a substring method with support for negative indexes:
public static String negSubstring(String str, int index1, int index2) {
return str.substring(toPosIndex(str, index1), toPosIndex(str, index2));
}
and if needed an equivalent to the version of substring with only one index parameter:
public static String negSubstring(String str, int index) {
return str.substring(toPosIndex(str, index));
}
(I realise the question is more than two years old, but figured that other new users might be interested in a general answer to the question).

Is there a left()-function for Java strings?

I have an string str of unknown length (but not null) and a given maximum length len, this has to fit in. All I want to do, is to cut the string at len.
I know that I can use
str.substring(0, Math.min(len, str.length()));
but this does not come handy, if I try to write stacked code like this
code = str.replace(" ", "").left(len)
I know that I can write my own function but I would prefer an existing solution. Is there an existing left()-function in Java?
There's nothing built in, but Apache commons has the StringUtils class which has a suitable left function for you.
If you don't want to add the StringUtils Library you can still use it the way you want like so:
String string = (string.lastIndexOf(",") > -1 )?string.substring(0, string.lastIndexOf(",")): string;
Use Split.
String str = "Result string Delimiter Right String";
System.out.println(str.split("Delimiter")[0].trim());
Output: "Result string"
No there is not left() in the String class, as you can refer API. But as #Mark said Apache StringUtils has several methods: leftPad(), rightPad(), center() and repeat(). You can also check
this:http://www.jdocs.com/lang/2.1/org/apache/commons/lang/StringUtils.html
You can use String Format
In this example the format specifier "%-9s" means minimum 9 characters left justified (-).
"%-9.9s" means maximum 9 characters.
System.out.println (String.format("%-9.9s","1234"));
System.out.println (String.format("%-9.9s","123456789ABCD"));
int len=9;
System.out.println (String.format("%-"+len+"."+len+"s","123456789ABCD"));
Prints:
1234
123456789
123456789
in OP's case it would be something like this:
static final int MAXLEN=9;
code = String.format("%-"+MAXLEN+"."+MAXLEN+"s",str.replace(" ", ""));
put the below function in a class:
public static String getLeftString(String st,int length){
int stringlength=st.length();
if(stringlength<=length){
return st;
}
return st.substring((stringlength-length));
}
in my case I want to get date only.
String s = "date:2021-01-01";
int n = s.length() - 10; //10 was the length of the date
String result = s.substring(n);
the result will be "2021-01-01";

Is there an equivalent of ucwords in java

In php, the method ucwords converts any string in a string where each words first character is in uppercase, and all other characters are lower case.
I always end up making my own implementation, and I'm wondering if a standard method exists.
That's called capitalization. Use Apache Commons's StringUtils to do that.
See more here:
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html
WordUtils is also worth looking at. See here
Otherwise it's a rather simple fix such as; String string1 = someString.substring(0,1).toUpperCase() + someString.substring(1);
You can put it in a function, and call it whenever you need. Saves you the trouble of maintaining libraries you don't need. (not that apache commons is ever trouble, but you get the point..)
EDIT: someString.substring(1) part can be written as someString.substring(1).toLowerCase() just to make sure that the rest of the string is in lowercase
I don't know about any direct equivalent, but you can always write one:
public static String capitalize(String input) {
if (input == null || input.length() <= 0) {
return input;
}
char[] chars = new char[1];
input.getChars(0, 1, chars, 0);
if (Character.isUpperCase(chars[0])) {
return input;
} else {
StringBuilder buffer = new StringBuilder(input.length());
buffer.append(Character.toUpperCase(chars[0]));
buffer.append(input.toCharArray(), 1, input.length()-1);
return buffer.toString();
}
}

JAVA: Read char from String to a certain char

Is there a method or way to read and keep reading chars from a string, putting them in a new string until there is a certain char.
Keep reading from < to > but no further.
Thankx
Of course. You will need:
the method String.charAt(int)
the + operator (or the method String.concat, or, if performance matters, the class StringBuilder)
the for statement
and perhaps an if-statement with a break statement
The statements and operators are explained in the Java Tutorial, and the method in the api javadoc.
(And no, I will not provide an implementation, since you would learn little by copying it)
You can actually write a utility that does that
public class StringUtil {
public static String copy(String str, char startChar, char endChar) {
int startPos = str.indexOf(startChar);
int endPos = str.lastIndexOf(endChar);
if (endPos < startPos) {
throw new RuntimeException("endPos < startPos");
}
char[] dest = new char[endPos - startPos + 1];
str.getChars(startPos, endPos, dest, 0);
return new String(dest);
}
};
PS Untested....
Alternatively, you can
String result = str.substring(startPos, endPos + 1); //If you want to include the ">" tag.
This may not be what you want but it will give you the desired string.
String desiredString="<Hello>".split("[<>]")[1];

Categories