做了个小练习,进行C++中char[]与string的转化,以及java中char[]与String的转化。 1. C++中char[]与string的转化 // StringConvertChar.cpp : Defines the entry point for the console application. #include "stdafx.h" #include <string> #include <iostream> using namespace std; int main(int argc, char* argv[]) { //方法一,c_str(),返回有”/0“的字符串数组 char cstr1[100]; string str1="Watson has something to do with semantics, "; cout<<"before方法一:/t"<<str1<<endl; strcpy( cstr1, str1.c_str() ); cout<<"after方法一:/t"<<cstr1<<endl; //方法二,data(),返回没有”/0“的字符串数组 string str2="but how to consolidate semantics into other field is a great problem. "; cout<<"before方法二:/t"<<str2<<endl; const char *cstr2=str2.data(); cout<<"after方法二:/t"; while(*cstr2!=NULL) { cout<<*cstr2; cstr2++; } cout<<endl; //方法三 copy string str3="So, we have to drill into this problem"; cout<<"before方法三:/t"<<str3<<endl; char cstr3[40]; str3.copy(cstr3,38,0); //这里5,代表复制几个字符,0代表复制的位置 *(cstr3+38)='/0'; //要手动加上结束符 cout<<"after方法三:/t"<<cstr3<<endl; return 0; } 2. Java中char[]与String的转化 public class StringAPIDemo02{ public static void main(String args[]){ String str = "hello world !!!@" ; char c[] = str.toCharArray() ; // 将字符串变为字符数组 for(int i=0;i<c.length;i++){ System.out.print(c[i] + "、"); } String str1 = new String(c) ; // 将全部的字符数组重新变为String String str2 = new String(c,0,5) ; // 将0~5的字符数组重新变为String System.out.println("/n"+str1) ; System.out.println(str2) ; } };