我有一个算法,从stdout读取一个名为'name'的字符串变量,然后创建一个存储名称的字符串数组..我试图在java中这样做,但首先,我不知道如何将名称传递给数组.在C或C++中,我可以轻松地完成这个:strcpy(arr,name); 但这些是字符串类型,并且我已经看到Java中没有等效的c_str().拜托,我该怎么做?
.... //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);
Run Code Online (Sandbox Code Playgroud)
您可能不需要复制字符串.
在C(和C++的部分)中,字符串表示为字符数组,其内容可以在程序的整个生命周期中更改 - 因此需要strcpy部分保留字符串内容.
但是,在Java中,字符串由String类表示,实例是不可变的,因此字符串的内容不能在程序的生命周期内改变.这意味着一旦你获得了对字符串的引用,就可以将它传递给任何其他Java代码,而不用担心它的内容会发生变化.
因此,在您的代码示例中,一旦您阅读了"name"字符串,您就可以将该值传递给MyClass构造函数:
System.out.println("Enter your name and press enter:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String name = br.readLine();
MyClass a = new MyClass(name);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6958 次 |
| 最近记录: |