what does a string in java mean in cpp? - java

I am really used to java programing now I want to use cpp and I was wondering what is a string called in cpp pretty silly question ? i am trying to use int but the compiler seems not to understand

In C++ a String is called string or preferably std::string and an int is called int. You wouldn't use an int instead of a string.
You appears to have two questions, one about string and another about int, which is confusing, but most likely you have a compilation error in your code which appears to be complaining about int when this is not the problem. I suggest you post a simple example of your code so we can see what you are trying to do.

The following types can be used as "strings" in C++:
1) std::string (defined in <string>)
#include <string>
std::string s = "hello world";
2) array of char
char s[16] = "hello";
char s[] = "world";
3) pointer to char (may actually point to an array)
const char* const globalConstString = "hello world";
void functionThatChangesString(char* s)
{
s[0] = '!';
}
Note that C-style char arrays and char pointers are less "safe" than C++ strings and should be used with care.

Related

C format specifier "%n" in Java

so I'm starting to learn java and I was wondering if I could use the "%n" parameter (from C printf()), which should write the number of bytes written up to the "%n" parameter:
this is it's use in C:
#include <stdio.h>
int main()
{
int val;
printf("ciao %n ciao\n", &val);
printf("val = %d\n", val);
return 0;
}
prints:
ciao ciao
val = 5
But when I try to use it in java:
public class CharTest
{
public static void main(String[] argv)
{
int value;
System.out.printf("\nNumber of bytes written up to now: %n\n", &value);
System.out.println(value);
}
}
The java compiler gives me this message:
CharTest.java:20: error: illegal start of expression
System.out.printf("\nNumber of bytes written up to now: %n\n", &value);
^
1 error
How do I solve this?
In C you can pass parameters by reference or change the value of variables passed to functions by passing a pointer to them, the %n specifier stores the number of characters written so far in value and in order to do that you had to pass the pointer to value with &value.
In Java it's not possible to pass parameters by reference or to pass pointers of variables and the same syntax is not possible, & operator is bitwise and. The printf %n specifier in Java prints a platform specific line separator.
You can't do it in Java at all. There is no conversion that would correspond to %n of the printf C. Instead, you can use the String.format to format the string
String s = String.format("\nNumber of *%s* written up to now: ", "characters");
then check the number of characters in s, and format that separately:
int len = s.length()
String result = String.format("%s%d\n", s, len);
Lastly, do note that unlike in C where char is exact synonym of byte, in Java the strings do not even consist of bytes, but Unicode/UTF-16 codepoints. Asking how many bytes are written by a string formatting operation is meaningless.

JAVA (Android) bitwise operator on strings

I am getting mad, i need to create a token using this operator
PHP
a = "hello";
b = "world";
token = a | b;
well i need create the same in java [android] but i ever get error.
I alredy try to:
- cast the 2 strings to long but obvisuly i get an error on casting
- cast the 2 string in BitSet
- cast the 2 strings in Bit Array
but the final result was ever an error.
Someone can suggest me some tips please ?
I assume that you want to perform a bitwise operation on strings(which performs a bitwise operation on ASCII values of characters of these string in PHP). There is no such operator for String in Java, but you can do it using BitSet:
public String or(String a, String b) throws UnsupportedEncodingException {
final String charsetName = "US-ASCII";
BitSet aBitSet = BitSet.valueOf(a.getBytes(charsetName));
aBitSet.or(BitSet.valueOf(b.getBytes(charsetName)));
return new String(aBitSet.toByteArray(), Charset.forName(charsetName));
}
As Sotirios said, you are probably(?) trying to concatenate strings. If that's the case, then String token=a+b; should do the job. Again, it's unclear what you ask.. You might want to take a look at the String documentation.

create short int array in c like java short[]

Java:
byte[] arr1=new byte[]{0x01};
String aa = "helloo";
short[] s1 = new short[1]; // **
s1[0] = 246; // **
Object[] obj = new Object[]{s1,arr1,aa}
C:
signed char a1[] = {0x01};
char *str = "helloo";
short int st1[] = {246}; // **
char* c [] = {st1,str1,c2};
Is short int st1[] = {246} correct? And I am getting this error:
"illegal implicit conversion from 'short *' to 'char *'".
How to assign short to char?
char* c []
is an array of pointers, not an array of chars.
Use something like
short st1[] = { 246 };
char* str = "helloo";
char c [] = {st1[0], str[0], str[1], str[2], str[3], str[4], str[5]};
str[i] gets individual characters, since 'char* str' points to the first element of an array.
If you need an array of string, then make it
char tmp[1024];
// itoa is the conversion of st1[0] to string
char* c[] = { itoa(st1[0], tmp, 10), str };
Cast st1 to a char*. I.e.:
char* c [] = {(char*)st1,str1,c2};
Note that you'll have to cast the pointer back to short* when accessing the elements it points to if you want to get the correct data.
C++ doesn't have a base Object type. You will have to convert your strings all to a specific type.
std::string wtf[]= { std::string(a1, a1+ 1), std::string(st1, st1+ 1), std::string(str) }; // don't forget to #include <string>
In C or C++ there is no common base class for all types (like Java's Object), the best you can use is void* c[]=...; (void* stands for untyped pointers, so it can hold anything) or explicitely cast to the desired type (but then it's undefined to access a short via a char-pointer).
Although its highly not recommended, the rough equivalent of the las line in c is:
void*  c [] = {st1,str1,c2};

Android JNI C simple append function

Id like to make a simple function, that return value of two Strings, basically:
java
public native String getAppendedString(String name);
c
jstring Java_com_example_hellojni_HelloJni_getAppendedString(JNIEnv* env, jobject thiz, jstring s) {
jstring sx = (*env)->GetStringUTFChars(env, s, NULL);
return ((*env)->NewStringUTF(env, "asd ")+sx);
}
It returns:
jni/hello-jni.c:32: warning: initialization discards qualifiers from pointer target type
jni/hello-jni.c:34: error: invalid operands to binary + (have 'char *' and 'char *')
The retval will be: "asd qwer", how can I do this?
jstring s1 = (*env)->NewStringUTF(env, "456");
jstring s2 = (*env)->NewStringUTF(env, "123");
jstring sall=strcat(s1, s2);
return sall;
Only returns "456"
There are a few issues here:
GetStringUTFChars returns a jbyte * (a null-terminated C string), not a jstring. You need this C string to do string manipulation in C.
You need to call ReleaseStringUTFChars when you're done with it.
You need to allocate enough memory to hold the concatenated string, using malloc.
As ethan mentioned, you need to concatenate your two C strings with strcat. (You cannot do this with the + operator. When applied to a pointer, + returns the pointer from the offset of the original pointer.)
Remember to free the memory you allocated after you're done with it (ie, after it's been interned as a Java string.)
You should do something along the lines of:
char *concatenated;
const jbyte *sx;
jstring retval;
/* Get the UTF-8 characters that represent our java string */
sx = (*env)->GetStringUTFChars(env, s, NULL);
/* Concatenate the two strings. */
concatenated = malloc(strlen("asd ") + strlen(sx) + 1);
strcpy(concatenated, "asd ");
strcat(concatenated, sx);
/* Create java string from our concatenated C string */
retval = (*env)->NewStringUTF(env, concatenated);
/* Free the memory in sx */
(*env)->ReleaseStringUTFChars(env, s, sx);
/* Free the memory in concatenated */
free(concatenated);
return retval;
You can't concatenate two char* with + in c++. Try using strcat instead.
http://www.cplusplus.com/reference/clibrary/cstring/strcat/
EDIT:
from the documentation for strcat:
char * strcat ( char * destination, const char * source );
Concatenate strings
Appends a copy of the source string to the destination string. The terminating null character in destination is overwritten by the first character of source, and a new null-character is appended at the end of the new string formed by the concatenation of both in destination.
This means that the first argument to strcat needs to have enough memory allocated to fit the entire concatenated string.

Convert ICU4C byte to java char

I am accessing an ICU4C function through JNI which returns a UChar * (i.e. unicode character array).... I was able to convert that to jbyteArray by equating each member of the UChar array to a local jbyte[] array that I created and then I returned it to Java using the env->SetByteArrayRegion() function... now I have the Byte[] array in Java but it's all gibberish pretty much.. Weird symbols at best... I am not sure where the problem might be... I am working with unicode characters if that matters... how do I convert the byte[] to a char[] in java properly? Something is not being mapped right... Here is a snippet of the code:
--- JNI code (altered slighter to make it shorter) ---
static jint testFunction(JNIEnv* env, jclass c, jcharArray srcArray, jbyteArray destArray) {
jchar* src = env->GetCharArrayElements(srcArray, NULL);
int n = env->getArrayLength(srcArray);
UChar *testStr = new UChar[n];
jbyte destChr[n];
//calling ICU4C function here
icu_function (src, testStr); //takes source characters and returns UChar*
for (int i=0; i<n; i++)
destChr[i] = testStr[i]; //is this correct?
delete testStr;
env->SetByteArrayRegion(destArray, 0, n, destChr);
env->ReleaseCharArrayElements(srcArray, src, JNI_ABORT);
return (n); //anything for now
}
-- Java code --
string wohoo = "ABCD bal bla bla";
char[] myChars = wohoo.toCharArray();
byte[] myICUBytes = new byte[myChars.length];
int value = MyClass.testFunction (myChars, myICUBytes);
System.out.println(new String(myICUBytes)) ;// produces gibberish & weird symbols
I also tried: System.out.println(new String(myICUBytes, Charset.forName("UTF-16"))) and it's just as gebberishy....
note that the ICU function does return the proper unicode characters in the UChar *... somewheres between the conversion to jbyteArray and Java that is is messing up...
Help!
destChr[i] = testStr[i]; //is this correct?
This looks like an issue all right.
JNI types:
byte jbyte signed 8 bits
char jchar unsigned 16 bits
ICU4C types:
Define UChar to be wchar_t if that is
16 bits wide; always assumed to be
unsigned.
If wchar_t is not 16 bits wide, then
define UChar to be uint16_t or
char16_t because GCC >=4.4 can handle
UTF16 string literals. This makes the
definition of UChar platform-dependent
but allows direct string type
compatibility with platforms with
16-bit wchar_t types.
So, aside from anything icu_function might be doing, you are trying to fit a 16-bit value into an 8-bit-wide type.
If you must use a Java byte array, I suggest converting to the 8-bit char type by transcoding to a Unicode encoding.
To paraphrase some C code:
UChar *utf16 = (UChar*) malloc(len16 * sizeof(UChar));
//TODO: fill data
// convert to UTF-8
UConverter *encoding = ucnv_open("UTF-8", &status);
int len8 = ucnv_fromUChars(encoding, NULL, 0, utf16, len16, &status);
char *utf8 = (char*) malloc(len8 * sizeof(char));
ucnv_fromUChars(encoding, utf8, len8, utf16, len16, &status);
ucnv_close(encoding);
//TODO: char to jbyte
You can then transcode this to a Java String using new String(myICUBytes, "UTF-8").
I used UTF-8 because it was already in my sample code and you don't have to worry about endianness. Convert my C to C++ as appropriate.
Have you considered using ICU4J?
Also, when converting your bytes to a string, you will need to specify a character encoding. I'm not familiar with the library in question, so I can't advise you further, but perhaps this will be "UTF-16" or similar?
Oh, and it's also worth noting that you might simply be getting display errors because the terminal you're printing to isn't using the correct character set and/or doesn't have the right glyphs available.

Categories