Possible Duplicate:
Reverse “Hello World” in Java
How to print the reverse of a string?
string s="sivaram";
with out using the string handling functions
Assuming a strict interpretation of your question and that you can't use ANY of the methods provided by the String / StringBuilder classes (which I suppose is not the intention), you can use reflection to access the char array directly:
public static void main(String[] args) throws ParseException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
String s = "abc";
Field stringValue = String.class.getDeclaredField("value");
stringValue.setAccessible(true);
char[] chars = (char[]) stringValue.get(s);
//now reverse
}
All functions that access the contents of a String in Java are members of the String class, therefore all are 'string functions.' Thus, the answer to your question as written is 'it cannot be done.'
with out using the string handling functions
Sure. Get the underlying char[] and then use a standard C style reversal of the characters and then build a new String from the reversed char[]
char[] chars = s.toCharArray();
//Now just reverse the chars in the array using C style reversal
String reversed = new String(chars);//done
I will not code this since this is definetely homework. But this is enough for you to get started
As far I am getting your question, this way should be working for you:
String str = "sivaram" ;//just an example (can be any string)
String newString = "" ;
for(int i=str.length()-1;i>-1;i--)
newString += str.charAt(i) ;
public static void main(String args[]){
char[] stringArray;
stringArray = s.toCharArray();
for(start at end of array and go to beginning)
System.out.print( s.charAt( i));
}
it's not possible to not use any string functions, I have a code that only uses two...
public String reverseString(String str)
{
String output = "";
int len = str.length();
for(int k = 1; k <= str.length(); k++, len--)
{
output += str.substring(len-1,len);
}
return output;
}
Related
Similar to this, I need the string equivalent of a net.sf.json.JSON object expressed entirely in ASCII characters.
new JSONObject().put("JSON", "帮").toString();
to return
{"JSON":"\u5E2E"}
not
{"JSON":"帮"}
Are you looking for a JSONObject based solution or normal java solution?
I am not sure is JsonObject have any such functionality. But a vaniall java based approach would be
public static void main(String[] args){
String s = "帮";
String s1 = "";
for (int i = 0; i < s.length(); i++)
s1 = s1+"\\u" + Integer.toHexString(s.charAt(i) | 0x10000).substring(1);
System.out.println(s1);
}
I have a String in java :
String str = "150,def,ghi,jkl";
I want to get sub string till first comma, do some manipulations on it and then replace it by modified string.
My code :
StringBuilder sBuilder = new StringBuilder(str);
String[] temp = str.split(",");
String newVal = Integer.parseInt(temp[0])*10+"";
int i=0;
for(i=0; i<str.length(); i++){
if(str.charAt(i)==',') break;
}
sBuilder.replace(0, i, newVal);
What is the best way to do this because I am working on big data this code will be called millions of times, I am wondering if there is possibility of avoiding for loop.
You also can use the method replace() of String Object itself.
String str = "150,def,ghi,jkl";
String[] temp = str.split(",");
String newVal = Integer.parseInt(temp[0])*10+"";
String newstr = newVal + str.substring(str.indexOf(","),str.length());
String str = "150,def,ghi,jkl";
String newVal = Integer.parseInt(str.substring(0,str.indexOf(",")))*10+"";
This should at least avoid excessive String concatenation and regular expressions.
String prefix = sBuilder.substring(0, sBuilder.indexOf(","));
String newVal = ...;
sBuilder.replace(0, newVal.length(), newVal);
Don't now if this is useful to you but we often use :
org.springframework.util.StringUtils
In the StringUtils class you have alot of useful methods for comma seperated files.
I have a Character array (not char array) and I want to convert it into a string by combining all the Characters in the array.
I have tried the following for a given Character[] a:
String s = new String(a) //given that a is a Character array
But this does not work since a is not a char array. I would appreciate any help.
Character[] a = ...
new String(ArrayUtils.toPrimitive(a));
ArrayUtils is part of Apache Commons Lang.
The most efficient way to do it is most likely this:
Character[] chars = ...
StringBuilder sb = new StringBuilder(chars.length);
for (Character c : chars)
sb.append(c.charValue());
String str = sb.toString();
Notes:
Using a StringBuilder avoids creating multiple intermediate strings.
Providing the initial size avoids reallocations.
Using charValue() avoids calling Character.toString() ...
However, I'd probably go with #Torious's elegant answer unless performance was a significant issue.
Incidentally, the JLS says that the compiler is permitted to optimize String concatenation expressions using equivalent StringBuilder code ... but it does not sanction that optimization across multiple statements. Therefore something like this:
String s = ""
for (Character c : chars) {
s += c;
}
is likely to do lots of separate concatenations, creating (and discarding) lots of intermediate strings.
Iterate and concatenate approach:
Character[] chars = {new Character('a'),new Character('b'),new Character('c')};
StringBuilder builder = new StringBuilder();
for (Character c : chars)
builder.append(c);
System.out.println(builder.toString());
Output:
abc
First convert the Character[] to char[], and use String.valueOf(char[]) to get the String as below:
char[] a1 = new char[a.length];
for(int i=0; i<a.length; i++) {
a1[i] = a[i].charValue();
}
String text = String.valueOf(a1);
System.out.println(text);
It's probably slow, but for kicks here is an ugly one-liner that is different than the other approaches -
Arrays.toString(characterArray).replaceAll(", ", "").substring(1, characterArray.length + 1);
Probably an overkill, but on Java 8 you could do this:
Character[] chars = {new Character('a'),new Character('b'),new Character('c')};
String value = Arrays.stream(chars)
.map(Object::toString)
.collect( Collectors.joining() );
At each index, call the toString method, and concatenate the result to your String s.
how about creating your own method that iterates through the list of Character array then appending each value to your new string.
Something like this.
public String convertToString(Character[] s) {
String value;
if (s == null) {
return null;
}
Int length = s.length();
for (int i = 0; i < length; i++) {
value += s[i];
}
return value;
}
Actually, if you have Guava, you can use Chars.toArray() to produce char[] then simply send that result to String.valueOf().
int length = cArray.length;
String val="";
for (int i = 0; i < length; i++)
val += cArray[i];
System.out.println("String:\t"+val);
This question already has answers here:
Replace a character at a specific index in a string?
(9 answers)
Closed 7 years ago.
I am trying to replace a character at a specific position of a string.
For example:
String str = "hi";
replace string position #2 (i) to another letter "k"
How would I do this?
Thanks!
Petar Ivanov's answer to replace a character at a specific index in a string question
String are immutable in Java. You can't change them.
You need to create a new string with the character replaced.
String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);
Or you can use a StringBuilder:
StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');
System.out.println(myName);
Kay!First of all, when dealing with strings you have to refer to their positions in 0 base convention. This means that if you have a string like this:
String str = "hi";
//str length is equal 2 but the character
//'h' is in the position 0 and character 'i' is in the postion 1
With that in mind, the best way to tackle this problem is creating a method to replace a character at a given position in a string like this:
Method:
public String changeCharInPosition(int position, char ch, String str){
char[] charArray = str.toCharArray();
charArray[position] = ch;
return new String(charArray);
}
Then you should call the method 'changeCharInPosition' in this way:
String str = "hi";
str = changeCharInPosition(1, 'k', str);
System.out.print(str); //this will return "hk"
If you have any questions, don't hesitate, post something!
Use StringBuilder:
StringBuilder sb = new StringBuilder(str);
sb.setCharAt(i - 1, 'k');
str = sb.toString();
To replace a character at a specified position :
public static String replaceCharAt(String s, int pos, char c) {
return s.substring(0,pos) + c + s.substring(pos+1);
}
If you need to re-use a string, then use StringBuffer:
String str = "hi";
StringBuffer sb = new StringBuffer(str);
while (...) {
sb.setCharAt(1, 'k');
}
EDIT:
Note that StringBuffer is thread-safe, while using StringBuilder is faster, but not thread-safe.
I can use this:
String str = "TextX Xto modifyX";
str = str.replace('X','');//that does not work because there is no such character ''
Is there a way to remove all occurrences of character X from a String in Java?
I tried this and is not what I want: str.replace('X',' '); //replace with space
Try using the overload that takes CharSequence arguments (eg, String) rather than char:
str = str.replace("X", "");
Using
public String replaceAll(String regex, String replacement)
will work.
Usage would be str.replace("X", "");.
Executing
"Xlakjsdf Xxx".replaceAll("X", "");
returns:
lakjsdf xx
If you want to do something with Java Strings, Commons Lang StringUtils is a great place to look.
StringUtils.remove("TextX Xto modifyX", 'X');
String test = "09-09-2012";
String arr [] = test.split("-");
String ans = "";
for(String t : arr)
ans+=t;
This is the example for where I have removed the character - from the String.
Hello Try this code below
public class RemoveCharacter {
public static void main(String[] args){
String str = "MXy nameX iXs farXazX";
char x = 'X';
System.out.println(removeChr(str,x));
}
public static String removeChr(String str, char x){
StringBuilder strBuilder = new StringBuilder();
char[] rmString = str.toCharArray();
for(int i=0; i<rmString.length; i++){
if(rmString[i] == x){
} else {
strBuilder.append(rmString[i]);
}
}
return strBuilder.toString();
}
}
I like using RegEx in this occasion:
str = str.replace(/X/g, '');
where g means global so it will go through your whole string and replace all X with '';
if you want to replace both X and x, you simply say:
str = str.replace(/X|x/g, '');
(see my fiddle here: fiddle)
Use replaceAll instead of replace
str = str.replaceAll("X,"");
This should give you the desired answer.
Evaluation of main answers with a performance benchmark which confirms concerns that the current chosen answer makes costly regex operations under the hood
To date the provided answers come in 3 main styles (ignoring the JavaScript answer ;) ):
Use String.replace(charsToDelete, ""); which uses regex under the hood
Use Lambda
Use simple Java implementation
In terms of code size clearly the String.replace is the most terse. The simple Java implementation is slightly smaller and cleaner (IMHO) than the Lambda (don't get me wrong - I use Lambdas often where they are appropriate)
Execution speed was, in order of fastest to slowest: simple Java implementation, Lambda and then String.replace() (that invokes regex).
By far the fastest implementation was the simple Java implementation tuned so that it preallocates the StringBuilder buffer to the max possible result length and then simply appends chars to the buffer that are not in the "chars to delete" string. This avoids any reallocates that would occur for Strings > 16 chars in length (the default allocation for StringBuilder) and it avoids the "slide left" performance hit of deleting characters from a copy of the string that occurs is the Lambda implementation.
The code below runs a simple benchmark test, running each implementation 1,000,000 times and logs the elapsed time.
The exact results vary with each run but the order of performance never changes:
Start simple Java implementation
Time: 157 ms
Start Lambda implementation
Time: 253 ms
Start String.replace implementation
Time: 634 ms
The Lambda implementation (as copied from Kaplan's answer) may be slower because it performs a "shift left by one" of all characters to the right of the character being deleted. This would obviously get worse for longer strings with lots of characters requiring deletion. Also there might be some overhead in the Lambda implementation itself.
The String.replace implementation, uses regex and does a regex "compile" at each call. An optimization of this would be to use regex directly and cache the compiled pattern to avoid the cost of compiling it each time.
package com.sample;
import java.util.function.BiFunction;
import java.util.stream.IntStream;
public class Main {
static public String deleteCharsSimple(String fromString, String charsToDelete)
{
StringBuilder buf = new StringBuilder(fromString.length()); // Preallocate to max possible result length
for(int i = 0; i < fromString.length(); i++)
if (charsToDelete.indexOf(fromString.charAt(i)) < 0)
buf.append(fromString.charAt(i)); // char not in chars to delete so add it
return buf.toString();
}
static public String deleteCharsLambda(String fromString1, String charsToDelete)
{
BiFunction<String, String, String> deleteChars = (fromString, chars) -> {
StringBuilder buf = new StringBuilder(fromString);
IntStream.range(0, buf.length()).forEach(i -> {
while (i < buf.length() && chars.indexOf(buf.charAt(i)) >= 0)
buf.deleteCharAt(i);
});
return (buf.toString());
};
return deleteChars.apply(fromString1, charsToDelete);
}
static public String deleteCharsReplace(String fromString, String charsToDelete)
{
return fromString.replace(charsToDelete, "");
}
public static void main(String[] args)
{
String str = "XXXTextX XXto modifyX";
String charsToDelete = "X"; // Should only be one char as per OP's requirement
long start, end;
System.out.println("Start simple");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++)
deleteCharsSimple(str, charsToDelete);
end = System.currentTimeMillis();
System.out.println("Time: " + (end - start));
System.out.println("Start lambda");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++)
deleteCharsLambda(str, charsToDelete);
end = System.currentTimeMillis();
System.out.println("Time: " + (end - start));
System.out.println("Start replace");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++)
deleteCharsReplace(str, charsToDelete);
end = System.currentTimeMillis();
System.out.println("Time: " + (end - start));
}
}
You will need to put the characters needs to be removed inside the square brackets during the time of replacement. The example code will be as following:
String s = "$116.42".replaceAll("[$]", "");
here is a lambda function which removes all characters passed as string
BiFunction<String,String,String> deleteChars = (fromString, chars) -> {
StringBuilder buf = new StringBuilder( fromString );
IntStream.range( 0, buf.length() ).forEach( i -> {
while( i < buf.length() && chars.indexOf( buf.charAt( i ) ) >= 0 )
buf.deleteCharAt( i );
} );
return( buf.toString() );
};
String str = "TextX XYto modifyZ";
deleteChars.apply( str, "XYZ" ); // –> "Text to modify"
This solution takes into acount that the resulting String – in difference to replace() – never becomes larger than the starting String when removing characters. So it avoids the repeated allocating and copying while appending character-wise to the StringBuilder as replace() does.
Not to mention the pointless generation of Pattern and Matcher instances in replace() that are never needed for removal.
In difference to replace() this solution can delete several characters in one swoop.
…another lambda
copying a new string from the original, but leaving out the character that is to delete
String text = "removing a special character from a string";
int delete = 'e';
int[] arr = text.codePoints().filter( c -> c != delete ).toArray();
String rslt = new String( arr, 0, arr.length );
gives: rmoving a spcial charactr from a string
package com.acn.demo.action;
public class RemoveCharFromString {
static String input = "";
public static void main(String[] args) {
input = "abadbbeb34erterb";
char token = 'b';
removeChar(token);
}
private static void removeChar(char token) {
// TODO Auto-generated method stub
System.out.println(input);
for (int i=0;i<input.length();i++) {
if (input.charAt(i) == token) {
input = input.replace(input.charAt(i), ' ');
System.out.println("MATCH FOUND");
}
input = input.replaceAll(" ", "");
System.out.println(input);
}
}
}
You can use str = str.replace("X", ""); as mentioned before and you will be fine. For your information '' is not an empty (or a valid) character but '\0' is.
So you could use str = str.replace('X', '\0'); instead.