String

Python


In [1]:
s1 = str()
# in python `"` or `""` is the same
s2 = 'robinchen'
s2len = len(s2)
# last three char
print s2[-4:] # chen
print s2[5:9] # chen
s3 = s2[:5] # robin
print s3
s3 += 'chen'
print s3

# list in python is the same as ArrayList in Java
s2List = list(s3)
print s2[4] #n
# find index at the first
print s2.index('c')
print s2.find('c')


chen
chen
robin
robinchen
n
5
5

In python, there is no StringBuffer or String Builder. It is cheaper to use string in Python.

C++

#include <string>

// dynamic
string s1 = new string("helloworld");

// static
string s2 = "robin";
int s2len = s2.length();
s2 += "chen";
s2.substr(3,4);
s2.append("Jr.");
size_t ind = s2.find('c');

#include <cstring>
// copy to char array (mutable)   
const char *cstr = s2.c_str();
cout << "c_string (char arry) = " << cstr << endl;

// copy to an non-mutable char array
char *cstr2 = new char[s2.length() + 1];
strcpy(cstr2, s2.c_str());

cstr2[5]='z';
cout << "cstr2 = " << cstr2 << endl;
delete [] cstr2;

In [ ]: