参考网址
https://www.runoob.com/ ==》 各种语言的实用编程实例
https://zh.cppreference.com/ ==》 C/C++ 很全面的参考手册网址
字符串操作
字符串操作包含字符串的构造,查找,连接,拷贝,比较,截取,打印等操作,C++ stl/C库/JAVA 都有相应的函数/类支持
语言 | 操作函数 |
---|---|
JAVA | StringBuilder/StringBuffer/String/Scanner类 |
C++ STL | std::string stringstream类 |
C库函数 | strcpy,strncpy,strcmp 等函数 |
JAVA中使用StringBuilder/StringBuffer/String 类型
示例代码如下:
String 类型一旦确定不能更改,用于固定化字符串
StringBuilder/StringBuffer 用于经常改变字符串内容的场景,和C库函对照表如下:
C库函数 | JAVA方法 | 说明 |
---|---|---|
strcpy() | substring | 字符串拷贝 |
strncpy() | substring | 字符串拷贝 |
strcat() | concat | 字符串连接 |
strncat() | concat | 字符串连接 |
strcmp() | compareTo | 字符串比较 |
sprintf() | Format | 格式化字符串 |
strchr() | Indexof | 查找字符 |
strstr | Indexof | 查找字符串 |
strtok() | xxx | NA |
atoi(), atol(),atof() | Integer.parseInt() Long.parseLong() Float.parseFloat | 字符串转换为基本类型 |
gets | scanner.nextline | 从终端读取一行 |
fgets | scanner.nextline | 从文件中读取一行 |
puts | System.out.println | 输出一行到终端 |
JAVA 示例代码:
package demoProject;
public class StringDemo {
public void printString(String str) {
System.out.println(str);
}
private void constructString() {
String stra = "String Construct a";
printString(stra);
String strb = new String("String Construct b");
printString(strb);
char[] c = {'A','r','r','a','y'};
String strc = new String(c);
printString(strc);
String strd = new String(c, 0, 3);
printString(strd);
String stre = stra.substring(1,10);
printString(stre);
}
public void StringOperate() {
String stra = " String Operate";
System.out.println("Stra length" + stra.length() + " concat:" + stra.concat(" concate strb"));
//trim String
System.out.println("Stra substring trim" + stra.trim() +" is Empty:" + stra.isEmpty());
System.out.println("Stra toUpper" + stra.toUpperCase() + " toLowercase" + stra.toLowerCase());
System.out.println("Stra index of O " + stra.indexOf('O'));
System.out.println("Stra index of Operate " + stra.indexOf("Operate"));
char c = stra.charAt(2);
System.out.println("charAt(2) is" + c);
}
private int val = 100;
private float fval = 3.1415f;
private boolean bval = true;
public void FormatString() {
System.out.printf("Format printf val=%d, fval=%f,bval=%b\n",val,fval,bval);
String s = String.format("Format String val=%d, fval=%f,bval=%b\n",val,fval,bval);
System.out.println(s);
}
public void StringDemoOperate() {
//constructString();
//StringOperate();
FormatString();
StringOperate();
}
}
public class StringBufferDemo {
public void testStringBuilder() {
StringBuilder sb = new StringBuilder(10);
sb.append("This is my StringBuilder");
System.out.println(sb);
//could append all type
sb.append("HaHaHa");
sb.append(false);
sb.append(10);
System.out.println(sb);
//insert value
sb.insert(5, "InsertValue");
System.out.println(sb);
//delete value
sb.delete(10, 20);
System.out.println("sb = " + sb + " sb length =" + sb.length());
//replace value
sb.replace(0, sb.length(), "Replaced Content");
System.out.println("sb = " + sb + " sb length =" + sb.length());
}
public void testStringBuffer() {
StringBuffer sbuffer = new StringBuffer();
sbuffer.append("This is my sBuffer");
System.out.println("sbuffer = " + sbuffer);
sbuffer.insert(0, "Insert value");
System.out.println("sbuffer = " + sbuffer);
sbuffer.delete(0, 5);
System.out.println("sbuffer = " + sbuffer);
sbuffer.replace(5, 10, "HHHHH");
System.out.println("sbuffer = " + sbuffer);
}
}
public class ScannerDemo {
//next cannot get blank space
public void testNextMethod() {
Scanner scan = new Scanner(System.in);
System.out.println("Next received");
if(scan.hasNext()) {
String str = scan.next();
System.out.println("get next string = " + str);
}
scan.close();
}
//next can get blank space
public void testNextLineMethod() {
Scanner scan = new Scanner(System.in);
System.out.println("nextLine received");
if(scan.hasNextLine()) {
String str = scan.nextLine();
System.out.println("get next string = " + str);
}
scan.close();
}
}
C库函数中的字符串操作函数
元素 | 说明 |
---|---|
strcpy() | 字符串拷贝 |
strncpy() | 字符串拷贝 |
strcat() | 字符串连接 |
strncat() | 字符串连接 |
strcmp() | 字符串比较 |
sprintf() | 格式化字符串 |
strchr() | 查找字符 |
strstr | 查找字符串 |
strtok() | NA |
atoi(), atol(),atof() | 字符串转换为基本类型 |
gets | 从终端读取一行 |
fgets | 从文件中读取一行 |
puts | 输出一行到终端 |
fputs | 输出一行到文件 |
C++ STL 中使用 std::string stringstream类型
参考网址: https://zh.cppreference.com/w/cpp/string/basic_string
C库函数 | stl string/stringstream | 说明 |
---|---|---|
strcpy() | substr,直接构造 | 字符串拷贝 |
strncpy() | substr,直接构造 | 字符串拷贝 |
strcat() | append | 字符串连接 |
strncat() | append | 字符串连接 |
strcmp() | compare | 字符串比较 |
sprintf() | stringstream | 格式化字符串 |
strchr() | find | 查找字符 |
strstr | contains | 查找字符串 |
strtok() | xxx | NA |
atoi(), atol(),atof() | stoi,stol,stof | 字符串转换为基本类型 |
gets | getline | 从终端读取一行 |
fgets | getline | 从文件中读取一行 |
puts | cout | 输出一行到终端 |
示例代码:
#include "stringDemo.h"
#include <iostream>
void stringDemo::printString(const string& str) {
cout << "print String = " << str << endl;
}
stringDemo::stringDemo() :mstr("Initilize value"){
printString(mstr);
string stra = mstr.append("append value");
printString(stra);
//strb as ==== constuct from char
string strb(4, '=');
printString(strb);
//construct from stra 0~7 character
string strc(stra, 0, 7);
printString(strc);
char marray[] = { 'H','e', 'l', 'l', 'o','\0'};
string strd(marray);
printString(strd);
string stre(marray, 0, 4);
printString(stre);
string strf({ 'C','O','D','E' });
printString(strf);
string strg = stra.substr(0,10);
printString(strg);
}
stringDemo::~ stringDemo() {
cout << "explict stringDemo ...." << endl;
}
void stringDemo::StrOperate() {
string stra = "This is demo string";
// size / empty
cout << "string a size:" << stra.size() << " stra is empty:" << stra.empty() << endl;
//get element
cout << "string a element[5] :" << stra[5] << " element[6]=" << stra.at(6) << endl;
}
=============================================================================
stringBufferDemo::stringBufferDemo() {
mstream << "Hello First line \n";
mstream << "Hello second line \n";
string mstr = "this is my string";
mstream << mstr;
mstream << 10;
mstream << 10.0000;
mstream << 'A';
cout << mstream.str() << endl;
}
线程相关接口
Linux C 线程操作函数接口
API接口 | 说明 |
---|---|
pthread_create() | 线程创建 |
pthread_join() | 等待线程退出 |
pthread_cond_init() | 线程等待条件量创建 |
pthread_cond_wait() | 线程阻塞等待条件量 |
pthread_cond_signal() | 线程唤醒 |
pthread_exit() | 线程退出 |
pthread_mutex_t | Mutex创建 |
pthread_mutex_lock() | Mutex lock |
pthread_mutex_unlock() | Mutex unlock |
Linux C 示例代码:
/*******************************************************************************
pthread_cond_init pthread_cond_init(pthread_cond_t *cv, \
const pthread_condattr_t *cattr);
attr 默认值为0
一般不接返回值
pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
函数将解锁mutex参数指向的互斥锁,并使当前线程阻塞在cv参数指向的条件变量上。
int pthread_cond_signal(pthread_cond_t *cv);
int pthread_cond_timedwait(pthread_cond_t *cv, pthread_mutex_t *mp, const structtimespec * abstime);
int pthread_cond_broadcast(pthread_cond_t *cv);
会解锁所有的线程
int pthread_cond_destroy(pthread_cond_t *cv);
* @History 2018-01-15
*******************************************************************************/
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// use posix therad must use this
#include <pthread.h>
pthread_t thread_handle[2];
//mutex for thread
static pthread_mutex_t mutex;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *thread1()
{
while(1)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
MI_PRINT("%s is running A\n",__FUNCTION__);
sleep(2);
pthread_mutex_unlock(&mutex);
sleep(1);
}
pthread_exit("thread1 exit");
}
void *thread2()
{
MI_U8 ret = 0;
MI_U8 loop = 0;
while(1)
{
pthread_mutex_lock(&mutex);
//ret = pthread_mutex_trylock(&mutex);
//perror("thread2 ----------\n");
MI_PRINT("%s is running B\n",__FUNCTION__);
sleep(1);
if( loop > 10 )
{
MI_PRINT("now we send thread signal \n");
pthread_cond_signal(&cond);
}
loop++;
pthread_mutex_unlock(&mutex);
sleep(1);
}
pthread_exit("thread2 exit");
}
MI_U8 _demo_init(void)
{
// 默认的属性为 NULL
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&cond, NULL);
return 1;
}
int main(int argc,char * argv[])
{
MI_PRINT(" This is my posix thread demo! \n");
MI_U8 eRet = -1;
void *Ptr= NULL;
_demo_init();
memset(thread_handle,0x00,sizeof(pthread_t));
eRet = pthread_create(&thread_handle[0], NULL, thread1, NULL);
eRet = pthread_create(&thread_handle[1], NULL, thread2, NULL);
if(eRet)
goto FAIL;
// we use pthread join to get some extra value
pthread_join(thread_handle[1], &Ptr);
MI_PRINT("The return message is %s \n", (char *)Ptr);
pthread_join(thread_handle[0],NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 1;
FAIL:
perror("Thread Creat fail!! please check \n");
return 0;
}
网友评论