I have an algorithm that reads from the stdout into a string variable called ‘name’ and then creates a string array that stores the name..I tried to do this in java but first, I don’t know how to pass the name into the array. in C or C++, i could have just easily done this : strcpy(arr, name); but these are string types and there are no c_str() equivalent in Java that I have seen. Please, how do I do this?
.... //codes are here...
System.out.Println("enter your name and press enter:");
BufferedReader br = new BufferedReader(InputStreamReader(System.in));
String name = null;
try
{
name = br.readLine();
String[] arr = new String[name.length];
//wish this was C++;
strcpy(arr.c_str(), name.c_str()); //how do you copy the name string to the arr
//string?
}catch(IOException e)
{
System.out.Println(e.getMessage());
}
MyClass A = new MyClass(arr);
I think you are completely mixing up stuff here.
Either the assignment
name = br.readLine()will produce an error (because readLine() returns aStringnot aString[]) or the expressionname.lengthwill produce a compiler error because aStringdoes not have a propertylengthonly a methodlength()Secondly:
will create an array of
Stringobjects. It does not declare a String of length name.length.If you really want to store the value read from the Reader into an array of String objects, can directly assign this:
Will create an array with one element, that contains the value of the name variable.
But I don’t see why you would want to put that String instance into an array in the first place.
And last but not least: there is no need to copy the String you get around. You can safely work with that instance (e.g. return it from the method) because the
Stringclass is immutable in Java.