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);
}
Related
I have a string separated by semicolon like this:
"11;21;12;22;13;;14;24;15;25".
Look one value is missing after 13.
I Want to populate that missing number with 13(previous value) and store it into another string.
Try this.
static final Pattern PAT = Pattern.compile("([^;]+)(;;+)");
public static void main(String[] args) {
String input = "11;21;12;22;13;;;14;24;15;25";
String output = PAT.matcher(input)
.replaceAll(m -> (m.group(1) + ";").repeat(m.group(2).length()));
System.out.println(output);
}
output:
11;21;12;22;13;13;13;14;24;15;25
What have you tried so far?
You could solve this problem in many ways i think. If you like to use regular expression, you could do it that way: ([^;]*);;+.
Or you could use a simple String.split(";"); and iterate over the resulting array. Every empty string indicates that there was this ;;
String str = "11;21;12;22;13;;14;24;15;25";
String[] a = str.split(";");
for(int i=0; i<a.length; i++){
if(a[i].length()==0){
System.out.println(a[i-1]);
}
}
I'm facing a problem in replacing character in a string with its index.
e.g I wanna replace every '?' With its index String:
"a?ghmars?bh?" -> will be "a1ghmars8bh11".
Any help is truly appreciated.
P.s I need to solve this assignment today so I can pass it to my instructor.
Thanks in adv.
So far I get to manage replacing the ? With 0; through this piece of code:
public static void main(String[] args) {
String name = "?tsds?dsds?";
String myarray[] = name.split("");
for (int i = 0; i < myarray.length; i++) {
name = name.replace("?", String.valueOf(i++));
}
System.out.println(name);
output:
0tsds0dsds0
it should be:
0tsds5dsds10
For simple replace operations, String.replaceAll is sufficient. For more complex operations, you have to retrace partly, what this method does.
The documentation of String.replaceAll says that it is equivalent to
Pattern.compile(regex).matcher(str).replaceAll(repl)
whereas the linked documentation of replaceAll contains a reference to the method appendReplacement which is provided by Java’s regex package publicly for exactly the purpose of supporting customized replace operations. It’s documentation also gives a code example of the ordinary replaceAll operation:
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat two cats in the yard");
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "dog");
}
m.appendTail(sb);
System.out.println(sb.toString());
Using this template, we can implement the desired operation as follows:
String name = "?tsds?dsds?";
Matcher m=Pattern.compile("?", Pattern.LITERAL).matcher(name);
StringBuffer sb=new StringBuffer();
while(m.find()) {
m.appendReplacement(sb, String.valueOf(m.start()));
}
m.appendTail(sb);
name=sb.toString();
System.out.println(name);
The differences are that we use a LITERAL pattern to inhibit the special meaning of ? in regular expressions (that’s easier to read than using "\\?" as pattern). Further, we specify a String representation of the found match’s location as the replacement (which is what your question was all about). That’s it.
In previous answer wrong read question, sorry. This code replace every "?" with its index
String string = "a?ghmars?bh?das?";
while ( string.contains( "?" ) )
{
Integer index = string.indexOf( "?" );
string = string.replaceFirst( "\\?", index.toString() );
System.out.println( string );
}
So from "a?ghmars?bh?das?" we got "a1ghmars8bh11das16"
You are (more or less) replacing each target with the cardinal number of the occurrence (1 for 1st, 2 for 2nd, etc) but you want the index.
Use a StringBuilder - you only need a few lines:
StringBuilder sb = new StringBuilder(name);
for (int i = name.length - 1; i <= 0; i--)
if (name.charAt(i) == '?')
sb.replace(i, i + 1, i + "");
Note counting down, not up, allowing for the replacement index to be multiple digits, which if you counted up would change the index of subsequent calls (eg everything would get shuffled to the right by one char when the index of "?" was 10 or more).
I think this may work i have not checked it.
public class Stack{
public static void main(String[] args) {
String name = "?tsds?dsds?";
int newvalue=50;
int countspecialcharacter=0;
for(int i=0;i<name.length();i++)
{
char a=name.charAt(i);
switch(a)
{
case'?':
countspecialcharacter++;
if(countspecialcharacter>1)
{
newvalue=newvalue+50;
System.out.print(newvalue);
}
else
{
System.out.print(i);
}
break;
default:
System.out.print(a);
break;
}
}
}
}
Check below code
String string = "a?ghmars?bh?das?";
for (int i = 0; i < string.length(); i++) {
Character r=string.charAt(i);
if(r.toString().equals("?"))
System.out.print(i);
else
System.out.print(r);
}
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);
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;
}