2012-07-13 44 views
0

我有一個字符串接口(const char *值,uint32_t長度),我需要操作。C++中的字符串操作

1)I必須使它所有小寫

2)I必須刪除後的所有字符的「;」分號

任何人都可以幫助我指出任何可以做到這一點的C/C++庫嗎?沒有我必須遍歷char數組。

在此先感謝

+0

你的意思是 「沒有明確地迭代」?因爲,不管你使用什麼方法/庫,它必須通過所有的角色! – go4sri 2012-07-13 10:18:05

+1

助推是你的朋友! – 2012-07-13 10:18:17

+2

我想,OP的意思是:「我不想自己寫這個循環。」我知道,我是一個心靈讀者。 – 2012-07-13 10:19:23

回答

3

1)

std::transform(str.begin(), str.end(), str.begin(), ::tolower); 

2)

str = str.substr(0, str.find(";")); 
1

我建議你(2)第一,因爲這將可能給(1)減少工作做。

如果您堅持使用傳統的C函數,您可以使用strchr()來查找第一個';'並用'\ 0'(如果該字符串是可變的)替換它,或者使用指針算術複製到另一個緩衝區。

您可以使用tolower()將ASCII(我假設您使用ASCII)轉換爲小寫字母,但您必須遍歷剩餘的循環才能執行此操作。

例如:

const char* str = "HELLO;WORLD"; 

// Make a mutable string - you might not need to do this 
int strLen = strlen(str); 
char mStr[ strLen + 1]; 
strncpy(mStr, str, strLen); 

cout << mStr << endl; // Prints "HELLO;WORLD" 

// Get rid of the ';' onwards. 
char* e = strchr(mStr, ';'); 
*e = '\0'; 

cout << mStr << endl; // Prints "HELLO" 

for (char* p = mStr; p != e; *p = tolower(*p), p++); 

cout << mStr << endl; // Prints "hello" 
+0

謝謝,這些都是我需要的完美庫。 – CodeBlocks 2012-07-13 10:28:06

+0

@CodeBlocks:謝謝,但除非你有很好的理由堅持舊的C風格的功能,否則我強烈建議你給AljoshaBre的回答一下。正如你所看到的,從C++的角度來看,它更加優雅。 – 2012-07-13 10:38:44

2

在這裏看到:http://ideone.com/fwJx5

#include <string> 
#include <iostream> 
#include <algorithm> 

std::string interface(const char* value, uint32_t length) 
{ 
    std::string s(value, length); 
    std::transform(s.begin(), s.end(), s.begin(), [] (char ch) { return std::tolower(ch); }); 
    return s.substr(0, s.find(";")); 
} 

int main() 
{ 
    std::cout << interface("Test Case Number 1; ignored text", 32) << '\n'; 
} 

輸出:

test case number 1