I am trying to insert a character into a string using Processing.
After some reading around I tried out the following (I think Java) code:
1: String st = new String("abcde");
2: st = StringBuffer(st).insert(2, "C");
and got the following response:
the function StringBuffer(String) does not exist
Is there a different/simpler way of doing this? Do I need to use StringBuffer? I'm a fairly novice programmer so any help greatly appreciated.
Ok, so I've been looking at the processing 'Extended Language API' and there doesn't seem to be some function like that out of the box.
If you look at the String class's substring() function, you'll see an example where there is a String that is cut into two pieces at position 2. And then printed out with other characters between them. Will that help you any further?
String str1 = "CCCP";
String str2 = "Rabbit";
String ss1 = str1.substring(2); // Returns "CP"
String ss2 = str2.substring(3); // Returns "bit"
String ss3 = str1.substring(0, 2); // Returns "CC"
println(ss1 + ":" + ss2 + ":" + ss3); // Prints 'CP:bit:CC'
If we take your example, this would insert the 'C' at the right position:
String st = new String("abcde");
String p1 = st.substring(0,2); // "ab"
String p2 = st.substring(2); // "cde"
st = p1 + "C" + p2; // which will result in "abCcde"
Or create a function for it. Mind you, not super-robust (no checks for empty strings, overflow etc), but does the job:
String insert(original, toInsert, position){
String p1 = original.substring(0,position);
String p2 = original.substring(position);
return p1 + toInsert + p2;
}
...
String st = new String("abcde");
st = insert(st, "C", 2); // "abCcde"
st = insert(st, "D", 4); // "abCcDde"
tested at http://sketch.processing.org