java中的字符串分割太强大了,最近发现原来C++中也能实现。
首先来看一个leetcode上的题
[LeetCode] Simplify Path 简化路径
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = “/home/”, => “/home”
path = “/a/./b/../../c/”, => “/c”
click to show corner cases.
Corner Cases:
Did you consider the case where path = “/../”?
In this case, you should return “/”.
Another corner case is the path might contain multiple slashes ‘/’ together, such as “/home//foo/”.
In this case, you should ignore redundant slashes and return “/home/foo”.
这个题解了其是就是字符串分割,分割线是“/”,然后将分割好的字符串放到stack栈里面,当碰到“.”了就保留不变,当碰到”..”的时候,就pop出上一次存的字符串。用sstream快的不行
代码实现
public class Solution {
public String simplifyPath(String path) {
Stack<String> s = new Stack<>();
String[] p = path.split("/");
for (String t : p) {
if (!s.isEmpty() && t.equals("..")) {
s.pop();
} else if (!t.equals(".") && !t.equals("") && !t.equals("..")) {
s.push(t);
}
}
List<String> list = new ArrayList(s);
return "/" + String.join("/", list);
}
}
原题解来自http://www.cnblogs.com/grandyang/p/4347125.html
下面再看下它的简单使用
#include <sstream>
#include <string>
#include <iostream>
using namespace std;
int main(){
string text="I'm a monster";
stringstream ss(text);
string sub_str;
while(getline(ss,sub_str,' '))
cout<<sub_str<<endl;
return 0;
}
从代码中从简单就学会分割了。对于一般的没有要求特定方式的即以空格做为分割,如下面
#include <sstream>
#include <string>
#include <iostream>
using namespace std;
int main(){
string text="I'm a monster";
stringstream ss(text);
while(ss>>text)
cout<<text.c_str()<<endl;
return 0;
}
那么我们可以细挖一下:
库定义了三种类:istringstream、ostringstream和stringstream,分别用来进行流的输入、输出和输入输出操作。除了我觉得最强大的分割功能为,还有就是数据类型转化,如下
string到int的转换
string result=”10000”;
int n=0;
stream<<result;
stream>>n;//n等于10000
这其中最强大的莫过于to_string()函数了
如int、long、double等等转换成字符串,要使用以一个string类型和一个任意值t为参数的to_string()函数。to_string()函数将t转换为字符串并写入result中。使用str()成员函数来获取流内部缓冲的一份拷贝:
整个函数原型跟上面很像
template<class T>
void to_string(string & result,const T& t)
{
ostringstream oss;//创建一个流
oss<<t;//把值传递如流中
result=oss.str();//获取转换后的字符转并将其写入result
}
to_string(s1,10.5);//double到string
to_string(s2,123);//int到string
to_string(s3,true);//bool到string
当然了还有convert函数,但感觉没鸟用了。
节选自 http://wuyani.blog.163.com/blog/static/19207521920118232577206/